SwiftJuniorMCQ

What are `willSet` and `didSet` property observers?

Test your knowledge:

Explanation & Code

Answer: willSet runs just before a new value is stored and didSet runs immediately after, letting you react to every change to a property.

  • willSet receives the incoming value as newValue (renamable: willSet(newTotal)).
  • didSet receives the previous value as oldValue (renamable: didSet(previous)).

Code Example:

class StepCounter {
    var totalSteps: Int = 0 {
        willSet {
            print("About to set totalSteps to \(newValue)")
        }
        didSet {
            if totalSteps > oldValue {
                print("Added \(totalSteps - oldValue) steps")
            }
        }
    }
}

let counter = StepCounter()
counter.totalSteps = 200
// About to set totalSteps to 200
// Added 200 steps
counter.totalSteps = 360
// About to set totalSteps to 360
// Added 160 steps

Common iOS uses:

  • Refresh UI when a model changes (var items: [Item] = [] { didSet { tableView.reloadData() } })
  • Validate or clamp a value
  • Persist a setting to UserDefaults whenever it changes

Key Points:

  • Observers are called on every set, even when the new value equals the current value.
  • Observers only work on stored properties you declare, or on inherited properties via override.

Rate your understanding:

Ready to practice more Swift?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.