Swift properties include stored, computed, lazy, and property observers—unifying fields and accessors without Java-style getter/setter boilerplate.
Stored and computed
struct Rect {
var width: Double
var height: Double
var area: Double { width * height }
}
Observers and lazy
var score: Int = 0 {
willSet { print("changing to \(newValue)") }
didSet { print("was \(oldValue)") }
}
lazy var loader = ExpensiveLoader()
lazy delays initialization until first access—common in reference types loading resources.
Important interview questions and answers
- Q: Computed property vs method?
A: Computed properties for side-effect-free derived values; methods when work is expensive or has parameters beyond self. - Q: lazy on structs?
A: Allowed but mutating—lazystored properties requiremutatingaccess on struct methods because they change storage.
Self-check
- What triggers willSet and didSet?
- When is a lazy property initialized?
Pitfall: lazy on struct properties requires mutating access because initialization mutates storage.
Interview prep
- Computed vs method?
Computed for side-effect-free derived values; methods when parameterized work.
- lazy when?
Deferred expensive initialization until first access.