What if your app could automatically notice and react to changes without you writing extra code every time?
Why Property observers (willSet, didSet) in Swift? - Purpose & Use Cases
Imagine you have a simple app that tracks a user's score. Every time the score changes, you want to update the screen and maybe save the new score. Without property observers, you have to remember to add extra code everywhere you change the score.
This manual way is slow and easy to forget. If you miss updating the screen or saving the score in one place, your app shows wrong info or loses data. It's like having to remember to turn off every light in a big house manually -- easy to miss one!
Property observers like willSet and didSet let you watch a property for changes in one place. You write the update code once, and it runs automatically whenever the property changes. This keeps your code clean and reliable.
score = 10
updateScreen()
saveScore()var score: Int = 0 { willSet { print("Score will change to \(newValue)") } didSet { updateScreen(); saveScore() } }
This lets you react instantly and safely to changes, making your app smarter and easier to maintain.
Think of a fitness app that updates your daily step count. With property observers, the app can automatically refresh the display and sync data whenever your step count changes, without extra code everywhere.
Manually tracking changes is error-prone and repetitive.
Property observers centralize change handling in one place.
They make your code cleaner, safer, and easier to update.
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
