Property Observers
A property observer is a little alarm that goes off right before or right after a property's value changes, so you can react to it.
In this page:
didSet Observer
A didSet block runs immediately after a property's value has changed, and can access the previous value via the implicit oldValue parameter.
Example: didSet Observer
struct ScoreTracker {
var score: Int = 0 {
didSet {
print("Score changed from \(oldValue) to \(score)")
}
}
}
var tracker = ScoreTracker()
tracker.score = 10
tracker.score = 25
Login to try C/C++/Java/PHP code in the editor
willSet Observer
A willSet block runs just before a property changes, and can access the incoming value via the implicit newValue parameter.
Example: willSet Observer
struct Thermostat {
var temperature: Int = 70 {
willSet {
print("About to change from \(temperature) to \(newValue)")
}
}
}
var thermostat = Thermostat()
thermostat.temperature = 75
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Trying to add
willSet/didSetto a computed property; observers only work on stored properties (or overridden inherited properties). - Forgetting
didSetreceives the OLD value asoldValue, whilewillSetreceives the upcoming NEW value asnewValue. - Setting the property again inside its own
didSetwithout a guard condition, risking infinite recursion in more complex cases.
Chapter Summary
willSetruns just before a stored property's value changes;didSetruns just after.- Inside
willSet, the implicit parameternewValueholds the value about to be set. - Inside
didSet, the implicit parameteroldValueholds the previous value. - Property observers only apply to stored properties, not computed ones.
🔒
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: