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?"
Practice
willSet property observer do in Swift?Solution
Step 1: Understand the role of
willSetwillSetruns code right before the property value changes.Step 2: Compare with
didSetdidSetruns code after the value changes, so it is different fromwillSet.Final Answer:
It runs code just before the property value changes. -> Option BQuick Check:
willSet = before change [OK]
- Confusing willSet with didSet
- Thinking willSet stops the change
- Assuming willSet initializes the property
didSet observer to a Swift property score?Solution
Step 1: Recall property observer syntax
Property observers must be inside braces after property declaration with initial value.Step 2: Check each option
var score: Int = 0 { didSet { print("Score changed") } } correctly declaresscorewith initial value and braces containingdidSet.Final Answer:
var score: Int = 0 { didSet { print("Score changed") } } -> Option CQuick Check:
Correct syntax uses braces after initial value [OK]
- Missing braces around didSet block
- No initial value for stored property
- Placing didSet outside property declaration
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()
counter.count = 5Solution
Step 1: Understand willSet and didSet order
willSet runs before the value changes, printing the new value. didSet runs after, printing old and new values.Step 2: Trace the code execution
Setting count to 5 triggers willSet printing "About to set count to 5", then didSet printing "Count changed from 0 to 5".Final Answer:
About to set count to 5 Count changed from 0 to 5 -> Option AQuick Check:
willSet before, didSet after change [OK]
- Mixing order of willSet and didSet prints
- Confusing oldValue and newValue
- Ignoring that willSet runs before assignment
struct Temperature {
var celsius: Double {
willSet(newTemp) {
print("Temperature will change to \(newTemp)")
}
didSet {
print("Temperature changed from \(oldValue) to \(celsius)")
}
}
}
var temp = Temperature(celsius: 25)
temp.celsius = 30Solution
Step 1: Check property declaration rules
Stored properties in structs must have initial values or be optional unless initialized in init.Step 2: Analyze the code
Propertycelsiushas no initial value and no initializer, causing error.Final Answer:
Stored property must have an initial value or be optional. -> Option DQuick Check:
Stored properties need initial values [OK]
- Thinking willSet parameter name is invalid
- Assuming property observers disallowed in structs
- Ignoring missing initial value error
age property and prevent it from being set to a value less than the current age. Which approach using property observers is correct?Solution
Step 1: Understand property observer capabilities
Property observers cannot prevent assignment in willSet; they run before or after change but cannot stop it.Step 2: Choose correct way to revert invalid change
In didSet, you can detect invalid changes and reset the property back to oldValue to prevent decrease.Final Answer:
Use didSet to check if age decreased and reset it back to oldValue. -> Option AQuick Check:
didSet can revert changes, willSet cannot prevent them [OK]
- Trying to prevent assignment in willSet
- Assuming willSet can throw errors
- Not resetting property in didSet after invalid change
Ready to prove it?
Pass the test and this pattern moves unknown
