Property 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
willSet
is called before myProperty
is set. The new value is available as newValue
, and the old value is still available as myProperty
.didSet
is called after myProperty
is set. The old value is available as oldValue
, and the new value is now available as myProperty
.Note: didSet and willSet will not be called in the following cases:
didSet
or willSet
oldValue
and newValue
of didSet
and willSet
can 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)
and didSet(newValue)
are entirely legal, but will considerably confuse readers of your code.