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:
Syntax
var property: Type = initialValue {
willSet { /* newValue is available */ }
didSet { /* oldValue is available */ }
}
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
// Define a struct `ScoreTracker`
struct ScoreTracker {
// Call `0` with a trailing closure, storing the result in `score`
var score: Int = 0 {
didSet {
// Print "Score changed from \(oldValue) to \(score)" to the console
print("Score changed from \(oldValue) to \(score)")
}
}
}
// Declare a mutable variable `tracker`, initialized to `ScoreTracker()`
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
// Define a struct `Thermostat`
struct Thermostat {
// Call `70` with a trailing closure, storing the result in `temperature`
var temperature: Int = 70 {
willSet {
// Print "About to change from \(temperature) to \(newValue)" to the console
print("About to change from \(temperature) to \(newValue)")
}
}
}
// Declare a mutable variable `thermostat`, initialized to `Thermostat()`
var thermostat = Thermostat()
thermostat.temperature = 75
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: