0
0
Swiftprogramming~5 mins

Property observers (willSet, didSet) in Swift

Choose your learning style9 modes available
Introduction

Property observers let you watch and respond when a value changes. They help you run code right before or after a value updates.

You want to update the user interface when a value changes.
You need to validate or adjust a value before it is saved.
You want to log changes to a property for debugging.
You want to trigger other actions automatically when data changes.
Syntax
Swift
var propertyName: Type {
    willSet(newValue) {
        // code to run before the value changes
    }
    didSet(oldValue) {
        // code to run after the value changes
    }
}

willSet runs just before the new value is stored.

didSet runs right after the new value is stored.

Examples
This example prints messages before and after the score changes.
Swift
var score: Int = 0 {
    willSet {
        print("Score will change to \(newValue)")
    }
    didSet {
        print("Score changed from \(oldValue) to \(score)")
    }
}
This example checks the temperature after it changes and prints a warning if it's too hot.
Swift
var temperature: Double = 20.0 {
    didSet {
        if temperature > 30 {
            print("It's too hot!")
        }
    }
}
Sample Program

This program creates a light switch that prints messages before and after it changes state.

Swift
class LightSwitch {
    var isOn: Bool = false {
        willSet {
            print("Light will turn \(newValue ? "ON" : "OFF")")
        }
        didSet {
            print("Light was \(oldValue ? "ON" : "OFF"), now is \(isOn ? "ON" : "OFF")")
        }
    }
}

let light = LightSwitch()
light.isOn = true
light.isOn = false
OutputSuccess
Important Notes

You don't have to provide both willSet and didSet; you can use just one.

Inside willSet, the new value is available as newValue by default.

Inside didSet, the old value is available as oldValue by default.

Summary

Property observers let you run code before and after a property changes.

Use willSet to react before the value changes.

Use didSet to react after the value changes.