← 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.
Syntax
swift
var property: Type = initialValue {
    willSet { /* newValue is available */ }
    didSet { /* oldValue is available */ }
}

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
// Define a struct `ScoreTracker`
struct ScoreTracker {
    // Call `0` with a trailing closure, storing the result in `score`
    var score: Int = 0 {
        didSet {
            // Print "Score changed from \(oldValue) to \(score)" to the console
            print("Score changed from \(oldValue) to \(score)")
        }
    }
}
// Declare a mutable variable `tracker`, initialized to `ScoreTracker()`
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
// Define a struct `Thermostat`
struct Thermostat {
    // Call `70` with a trailing closure, storing the result in `temperature`
    var temperature: Int = 70 {
        willSet {
            // Print "About to change from \(temperature) to \(newValue)" to the console
            print("About to change from \(temperature) to \(newValue)")
        }
    }
}
// Declare a mutable variable `thermostat`, initialized to `Thermostat()`
var thermostat = Thermostat()
thermostat.temperature = 75
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.