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 and didset

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.

propertyObserver.zip

First make UI look something like this. I used stack views to build this very quickly.

Project UI

Copy the following code into your ViewController and make sure you connect your Outlets and Actions.

import UIKit

struct RGB {
var r: CGFloat
var g: CGFloat
var b: CGFloat
}

class ViewController: UIViewController {

@IBOutlet weak var rValueLabel: UILabel!
@IBOutlet weak var gValueLabel: UILabel!
@IBOutlet weak var bValueLabel: UILabel!

@IBAction func rPlusButton(_ sender: AnyObject) { rgb.r += 0.10 }
@IBAction func rMinusButton(_ sender: AnyObject) { rgb.r -= 0.10 }
@IBAction func gPlusButton(_ sender: AnyObject) { rgb.g += 0.10 }
@IBAction func gMinusButton(_ sender: AnyObject) { rgb.g -= 0.10 }
@IBAction func bPlusButton(_ sender: AnyObject) { rgb.b += 0.10 }
@IBAction func bMinusButton(_ sender: AnyObject) { rgb.b -= 0.10 }

var rgb: RGB = RGB(r: 0, g: 0, b: 0) {
willSet {
print("About to set RGB to: \(newValue)")
}
didSet {
print("Previous value for RGB was: \(oldValue)")
updateView()
}
}

func updateView() {
print("Red: \(rgb.r) Green: \(rgb.g) Blue: \(rgb.b)")
rValueLabel.text = "\(rgb.r)"
gValueLabel.text = "\(rgb.g)"
bValueLabel.text = "\(rgb.b)"
view.backgroundColor = UIColor(red: rgb.r, green: rgb.g, blue: rgb.b, alpha: 1)
}
}

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 updateView() function

Property Observers in Action

Property Observer 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.