3 min readFeb 9, 2026
SwiftHow to Use Property Observers
React to changes with willSet and didSet.
Steps
- Paste the code into a Swift file or playground.
- Run it once to verify the output.
- 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 = 2Notes
- Keep functions small and focused for reuse.
- Prefer safe APIs like optionals and guards.
