#257: Property Observers on Local Variables 🐤


We first looked at Swift's property observers back in Bite #179. They're a great way to know when a property's value is about to change, or just finished changing.

Traditionally, they look like this:

class Spaceship : NSObject {
  var name: String {
    didSet { print(name) }

Nothing too fancy here, just printing the latest value for name, anytime a ship's name changes.

This works great for properties on types, but it turns out we can actually use these same observers on local variables as well:

var name = "Tim Cook" {
  didSet { print(name) }

name = "Eddy Cue"
name = "Craig Federighi"

This prints:

Eddy Cue
Craig Federighi


Kelan Champagne mentions an interesting technique for super-simple value-change tracking:

var previousStatuses = [String]()
var awayMessage: String? = nil {
  willSet {
    guard let awayMessage = awayMessage else { return }

awayMessage = "out to lunch, brb"
awayMessage = "eating dinner"
awayMessage = "emo song lyrics"
awayMessage = nil

print("Previous: ", previousStatuses)

This prints:

Previous: ["out to lunch, brb", "eating dinner", "emo song lyrics"]

This technique might not make sense in many situations, but is a nice feature to know about in case we can ever benefit from it.

A huge thanks to both Kelan Champagne and Chris Eidhof for pointing this out!