0Pricing
Swift Academy · Lesson

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

  1. Value Types and Immutability
  2. The mutating Keyword
  3. Mutating and self Reassignment
  4. Non-mutating Alternatives
← Back to Swift Academy