Property Observers
suggest changeProperty observers respond to changes to a property’s value.
var myProperty = 5 {
willSet {
print("Will set to \(newValue). It was previously \(myProperty)")
}
didSet {
print("Did set to \(myProperty). It was previously \(oldValue)")
}
}
myProperty = 6
// prints: Will set to 6, It was previously 5
// prints: Did set to 6. It was previously 5
willSetis called beforemyPropertyis set. The new value is available asnewValue, and the old value is still available asmyProperty.didSetis called aftermyPropertyis set. The old value is available asoldValue, and the new value is now available asmyProperty.
Note: didSet and willSet will not be called in the following cases:
- Assigning an initial value
- Modifying the variable within its own
didSetorwillSet - The parameter names for
oldValueandnewValueofdidSetandwillSetcan also be declared to increase readability:
var myFontSize = 10 {
willSet(newFontSize) {
print("Will set font to \(newFontSize), it was \(myFontSize)")
}
didSet(oldFontSize) {
print("Did set font to \(myFontSize), it was \(oldFontSize)")
}
}
Caution: While it is supported to declare setter parameter names, one should be cautious not to mix names up:
willSet(oldValue)anddidSet(newValue)are entirely legal, but will considerably confuse readers of your code.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents