Property observers (willSet, didSet) in Swift - Time & Space Complexity
When we use property observers in Swift, we want to know how much extra work happens when a property changes.
We ask: How does the time to run grow as we change the property many times?
Analyze the time complexity of the following code snippet.
class Counter {
var count: Int = 0 {
willSet {
print("About to set count to \(newValue)")
}
didSet {
print("Count changed from \(oldValue) to \(count)")
}
}
}
let counter = Counter()
for i in 1...n {
counter.count = i
}
This code changes a property many times and runs code before and after each change.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop that sets the property
countrepeatedly. - How many times: The property is set
ntimes, triggering observers each time.
Each time the property changes, the observers run once. So if we change it 10 times, 10 observer calls happen.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 observer calls |
| 100 | About 100 observer calls |
| 1000 | About 1000 observer calls |
Pattern observation: The work grows directly with how many times the property changes.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of property changes.
[X] Wrong: "Property observers run only once no matter how many times the property changes."
[OK] Correct: Observers run every time the property changes, so the total work adds up with each change.
Understanding how property observers add work helps you explain performance when properties update often in real apps.
"What if the property observers did some heavy work inside? How would that affect the time complexity?"