← Back to Swift Course | Chapter 8: Structs & Classes | Lesson 6 of 9

Property Observers

A property observer is a little alarm that goes off right before or right after a property's value changes, so you can react to it.

didSet Observer

A didSet block runs immediately after a property's value has changed, and can access the previous value via the implicit oldValue parameter.

Example: didSet Observer

markup
struct ScoreTracker {
    var score: Int = 0 {
        didSet {
            print("Score changed from \(oldValue) to \(score)")
        }
    }
}
var tracker = ScoreTracker()
tracker.score = 10
tracker.score = 25

willSet Observer

A willSet block runs just before a property changes, and can access the incoming value via the implicit newValue parameter.

Example: willSet Observer

markup
struct Thermostat {
    var temperature: Int = 70 {
        willSet {
            print("About to change from \(temperature) to \(newValue)")
        }
    }
}
var thermostat = Thermostat()
thermostat.temperature = 75
Common Mistakes
  1. Trying to add willSet/didSet to a computed property; observers only work on stored properties (or overridden inherited properties).
  2. Forgetting didSet receives the OLD value as oldValue, while willSet receives the upcoming NEW value as newValue.
  3. Setting the property again inside its own didSet without a guard condition, risking infinite recursion in more complex cases.
Chapter Summary
  • willSet runs just before a stored property's value changes; didSet runs just after.
  • Inside willSet, the implicit parameter newValue holds the value about to be set.
  • Inside didSet, the implicit parameter oldValue holds the previous value.
  • Property observers only apply to stored properties, not computed ones.
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.