SwiftJuniorOpen-ended
Why can't you change a `var` property of a struct assigned to a `let` constant?
Explanation & Code
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,
letfreezes the value. - For a class,
letonly freezes which instance the constant refers to; the instance'svarproperties stay mutable. - The same rule explains why
mutatingmethods and computed setters can't be called on aletstruct.
Rate your understanding: