Property Observer in Swift
What is Property Observer
Property Observer observe and respond to changes in property’s value.
It is called every time a property’s value is set, even if the new value is the same as the old value.
You can use property observer with any stored property but not lazy properties.
It can be added also to any inherited property (computed or stored) by overriding them.
You do not need to add Property Observer for computed properties in your own class because you can always implement the property’s setter instead.
Property Observer will not run during initializers when a class is setting its own properties.
But property observers of a superclass will be called when a property is set in subclass initializer after the superclass initializer has been called.
How to use Property Observer in Swift
You have the option to implement two observers on a property
- willSet: which will be called just before setting the new value. It is passed a constant parameter containing the new value and it is called newValue by default but you can give it another name.
- didSet: is called after the new value is set. It is passed a constant parameter containing the old value and it is called oldValue by default but you can change it.
Property Observer example
var total = 0 { willSet { print("new value: \(newValue)") } didSet { print("old value: \(oldValue)") } }
Now assign a new int value to total anywhere in your class
total = 20
The console prints:
new value: 20 old value: 0
One very good example of using Property Observers is updating your UILabel displaying the total count so that any time anywhere the total changes the label display will change too.
Finally I recommend reading Enum in Swift and Associated Data