Value Types and Immutability
See how let prevents mutation of value types.
Structs Are Value Types
In Swift, struct and enum are value types. Assigning one to a new variable copies it.
struct Point { var x: Int; var y: Int }
var a = Point(x: 1, y: 2)
var copy = a
copy.x = 99
print(a.x, copy.x)let Locks the Whole Value
Declaring a struct with let makes the entire value immutable, including all its properties.
struct Counter { var value: Int }
let c = Counter(value: 0)
// c.value = 5 // compile error
print(c.value)All lessons in this course
- Value Types and Immutability
- The mutating Keyword
- Mutating and self Reassignment
- Non-mutating Alternatives