๐ŸŽ“ A1Learner
๐Ÿ”
0 of 36 lessons completed

Swift Property Observers

Property observers are blocks that run when a stored property is about to change or has just changed. The two observers are named willSet and didSet.

Both observers around a score

Making the game prints nothing, because the observers stay quiet for the starting value. Each score change then prints the willSet line before the didSet line.

struct Game {
    var score: Int = 0 {
        willSet {
            print("Score is about to become \(newValue)")
        }
        didSet {
            print("Score was \(oldValue)")
        }
    }
}
var game = Game()
game.score = 10
game.score = 25

A step tracker with didSet

The ready line prints before any observer line, which proves the tracker was made without firing didSet. Each steps change prints one line naming the old and new counts.

struct StepTracker {
    var steps: Int = 0 {
        didSet {
            print("Steps moved from \(oldValue) to \(steps)")
        }
    }
}
var tracker = StepTracker()
print("Tracker ready")
tracker.steps = 120
tracker.steps = 300

Reading the old value in willSet

Inside willSet the property still holds its old value. The line therefore names 5 as the current volume and 8 as the incoming one.

struct Radio {
    var volume: Int = 5 {
        willSet {
            print("Volume changing from \(volume) to \(newValue)")
        }
    }
}
var radio = Radio()
radio.volume = 8
print(radio.volume)

Example

struct Meter {
    var reading: Int = 100 {
        willSet {
            print("Next reading \(newValue)")
        }
        didSet {
            print("Previous reading \(oldValue)")
        }
    }
}
var meter = Meter()
meter.reading = 140
print(meter.reading)

Key points

  • willSet runs just before a new value is stored in the property.
  • Inside willSet, newValue holds the value about to be stored.
  • didSet runs just after the new value is stored in the property.
  • Inside didSet, oldValue holds the value that was just replaced.
  • Observers do not run when a property receives its first value while a value is being made.
  • Each later change runs the observers again.

In this example, the Meter struct starts with a reading of 100 and making it prints nothing. Assigning 140 runs willSet first, which prints Next reading 140. didSet runs next and prints Previous reading 100, and the final print shows the stored reading 140.

Note

An observer that only prints still runs on every change after the value is made.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

When does the didSet block of a property run?