Coding/Learn/swift/swift structures and value semantics
Swift Foundational Course
01.Introduction, Safety Philosophy & The Toolchain
02.Constants (let), Variables (var) & Type Inference
03.Strings, String Interpolation & Multiline Literals
04.Operators, Range Types & Nil-Coalescing
05.Control Flow: If, Switch Pattern Matching & Guard Statements
06.Optionals, Optional Binding & Optional Chaining
07.Arrays, Sets & Higher-Order Collection Operations
08.Dictionaries, Default Lookups & Tuples
09.Loops, Defer Execution & Labeled Statements
10.Functions, Argument Labels & In-Out Parameters
11.Closures, Trailing Closures & Shorthand Arguments
12.Enums, Raw Values & Associated Values (Tagged Unions)
13.Error Handling: Throwing Functions, Do-Catch & Try Options
14.Structures (struct), Value Semantics & Mutating Methods
15.Classes, Reference Semantics & Inheritance
16.Automatic Reference Counting (ARC), Weak & Unowned References
17.Properties: Stored, Computed, Observers (didSet) & Lazy
18.Protocols, Protocol Extensions & POP (Protocol-Oriented Programming)
19.Generics, Type Constraints & Associated Types
20.Capstone: Production Async/Await Cache & JSON API Engine
Course Certificate0%

Complete all lessons to earn

LearnStructures (struct), Value Semantics & Mutating Methods
14 / 20 0%
Lesson 14 of 20
10 mins read

Structures (struct), Value Semantics & Mutating Methods

PreviousNext Lesson
In Plain English

Structs are the building blocks of idiomatic Swift (SwiftUI, Foundation types). Learn value semantics (copy-on-assignment), automatic memberwise initializers, mutating methods, and why Apple recommends defaulting to structs over classes.

The Mental Model

"A struct is like an electronic spreadsheet file: when you email a copy to a colleague, they work on their own independent copy. Any edits they make never alter your original file."

Deep Dive: How It Works

Value Types: Assigning a struct to a new variable or passing it into a function creates an independent copy.

Memberwise Initializer: Swift generates an automatic constructor for structs based on their stored properties.

Mutating Methods: Methods on a struct that modify internal properties must be marked with the mutating keyword.

Copy-on-Write (CoW): Swift standard library collections (Array, Dictionary, String) are structs that copy storage only when mutated.

Syntax Blueprint

struct Point {
    var x: Double
    var y: Double
    mutating func move(dx: Double) { x += dx }
}

Define structs with stored properties and mark self-modifying functions with mutating.

PointCore Rules to Remember

Point star
Default to Structs: Apple recommends using structs as the default choice for data modeling in Swift.
Point star
Thread Safety: Value semantics eliminate shared mutable state, making code naturally safer for concurrency.
Point star
No Inheritance: Structs cannot inherit from other structs; use protocols and composition instead.

Common Beginner Traps & How to Fix Them

Mistake:Trying to call a mutating method on a struct instance declared with let.

Why it happens: let freezes the entire struct value, preventing mutating methods from changing any internal property.

How to fix: Declare the struct instance with var if you need to invoke mutating methods.

Pro Tip: If you define a custom init inside your struct body, Swift disables the memberwise initializer; define custom inits in an extension to preserve both!

Live Interactive Example

Hit Run Code to see it live
Value Semantics and Mutating Methods
Swift 5.10 / LLVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Output Console
Click "Run Code" to view the rendered output.
How it works: c2 was an independent copy of c1; mutating c2 had zero impact on c1.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Rectangle Struct with Area Method

  • PointDefine a struct Rectangle with properties var width: Double and var height: Double.
  • PointAdd a method area() -> Double returning width * height.
  • PointIn top-level code, create a Rectangle with width 4.0 and height 5.0, and print "Area: \(rect.area())".
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates