Browse Questions

Answer: Because a struct is a value type, declaring the instance with let makes the entire value immutable — including all of its var stored properties.

Code Example:

struct FixedLengthRange {
    var firstValue: Int
    let length: Int
}

let range = FixedLengthRange(firstValue: 0, length: 4)
// range.firstValue = 6 // ❌ Cannot assign to property: 'range' is a 'let' constant

var mutableRange = FixedLengthRange(firstValue: 0, length: 4)
mutableRange.firstValue = 6 // ✅
// mutableRange.length = 5  // ❌ 'length' is a 'let' constant

class Box { var value = 0 }
let box = Box()
box.value = 5 // ✅ — `let` fixes the reference, not the object it points to

Key Points:

  • For a struct, let freezes the value.
  • For a class, let only freezes which instance the constant refers to; the instance's var properties stay mutable.
  • The same rule explains why mutating methods and computed setters can't be called on a let struct.