What are lazy properties and property observers?
A stored property can run code when it is set or read through observers and modifiers.
willSetanddidSetobserve changes to a stored property.willSetreceives the new value,didSetthe old, and neither fires during initialisation.lazydefers creation until first access. It is useful for expensive setup that depends on other properties, and the property must bevar.
class ViewModel {
lazy var formatter = DateFormatter()
var score = 0 {
didSet {
print("changed from \(oldValue) to \(score)")
}
}
}
Computed properties with get and set do not store a value and are recalculated on each access; a get-only computed property is read-only. Observers are not called when setting from within the initialiser or from a designated initialiser delegation.
Lazy properties are not thread-safe by themselves. Use observers for lightweight side effects, not heavy work.