MasterOnce logo
Get the iOS App
3 min readFeb 9, 2026
Swift

How to Use Property Observers

React to changes with willSet and didSet.

Steps

  1. Paste the code into a Swift file or playground.
  2. Run it once to verify the output.
  3. Adjust the inputs to match your use case.

Copy and paste

import Foundation

struct Counter {
    var value: Int = 0 {
        didSet {
            print("Value changed to (value)")
        }
    }
}

var counter = Counter()
counter.value = 2

Notes

  • Keep functions small and focused for reuse.
  • Prefer safe APIs like optionals and guards.