What is a property observer?
Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value. - The Swift Programming Language
Using Property Observers
We have the option of two observers,
willset is called just before a value is stored
didset is called immediately after the new value is stored
Knowing this we can create an app that changes our view’s background color each time our RGB color is changed.
You can start the project from scratch or just download my sample project.
First make UI look something like this. I used stack views to build this very quickly.
Copy the following code into your ViewController and make sure you connect your Outlets and Actions.
Every time we change the property value for either r, g, or b our two observers are called.
willset prints our property’s new value
didset prints our property’s old value, changes the corresponding labels text, and called our
Property Observers in Action
What’s the significance?
Property Observers allow us to simplify our code by attaching code that runs when a change is observed.
In our example we could have set our label’s text and called
updateView() in each
@IBAction but we would’ve had to write the same code for EACH action, it’s always important to remember to follow the Don’t Repeat Yourself principle. The Property Observer allows us to be DRY and not WET.
Special thanks to @iankeen on the iOS Developers slack channel for helping understand the significance and cleaning up my code.