Property observers let you watch and respond when a value changes. They help you run code right before or after a value updates.
You want to update the user interface when a value changes.
You need to validate or adjust a value before it is saved.
You want to log changes to a property for debugging.
You want to trigger other actions automatically when data changes.
Syntax
Swift
var propertyName: Type {
willSet(newValue) {
// code to run before the value changes
}
didSet(oldValue) {
// code to run after the value changes
}
}
willSet runs just before the new value is stored.
didSet runs right after the new value is stored.
Examples
This example prints messages before and after the score changes.
Swift
var score: Int = 0 {
willSet {
print("Score will change to \(newValue)")
}
didSet {
print("Score changed from \(oldValue) to \(score)")
}
}
This example checks the temperature after it changes and prints a warning if it's too hot.
Swift
var temperature: Double = 20.0 {
didSet {
if temperature > 30 {
print("It's too hot!")
}
}
}
Sample Program
This program creates a light switch that prints messages before and after it changes state.
Swift
class LightSwitch {
var isOn: Bool = false {
willSet {
print("Light will turn \(newValue ? "ON" : "OFF")")
}
didSet {
print("Light was \(oldValue ? "ON" : "OFF"), now is \(isOn ? "ON" : "OFF")")
}
}
}
let light = LightSwitch()
light.isOn = true
light.isOn = false
OutputSuccess
Important Notes
You don't have to provide both willSet and didSet; you can use just one.
Inside willSet, the new value is available as newValue by default.
Inside didSet, the old value is available as oldValue by default.
Summary
Property observers let you run code before and after a property changes.
Use willSet to react before the value changes.
Use didSet to react after the value changes.
Practice
(1/5)
1. What does the willSet property observer do in Swift?
easy
A. It runs code after the property value changes.
B. It runs code just before the property value changes.
C. It prevents the property value from changing.
D. It initializes the property with a default value.
Solution
Step 1: Understand the role of willSet
willSet runs code right before the property value changes.
Step 2: Compare with didSet
didSet runs code after the value changes, so it is different from willSet.
Final Answer:
It runs code just before the property value changes. -> Option B
Quick Check:
willSet = before change [OK]
Hint: willSet runs before change, didSet runs after [OK]
Common Mistakes:
Confusing willSet with didSet
Thinking willSet stops the change
Assuming willSet initializes the property
2. Which of the following is the correct syntax to add a didSet observer to a Swift property score?
easy
A. var score: Int { didSet { print("Score changed") } }
B. var score: Int = 0 didSet { print("Score changed") }
C. var score: Int = 0 { didSet { print("Score changed") } }
D. var score: Int didSet { print("Score changed") }
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 declares score with initial value and braces containing didSet.
Final Answer:
var score: Int = 0 { didSet { print("Score changed") } } -> Option C
Quick Check:
Correct syntax uses braces after initial value [OK]
Hint: Use braces after initial value for observers [OK]
Common Mistakes:
Missing braces around didSet block
No initial value for stored property
Placing didSet outside property declaration
3. What will be printed when the following Swift code runs?
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 = 5
medium
A. About to set count to 5
Count changed from 0 to 5
B. Count changed from 0 to 5
About to set count to 5
C. About to set count to 0
Count changed from 0 to 5
D. Count changed from 5 to 0
About to set count to 5
Solution
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 A
Quick Check:
willSet before, didSet after change [OK]
Hint: willSet prints newValue, didSet prints oldValue and new value [OK]
Common Mistakes:
Mixing order of willSet and didSet prints
Confusing oldValue and newValue
Ignoring that willSet runs before assignment
4. Identify the error in this Swift code using property observers:
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 = 30
medium
A. Property observers cannot be used in structs.
B. The willSet parameter name cannot be custom like newTemp.
C. The struct cannot be instantiated with an initial value.
D. Stored property must have an initial value or be optional.
Solution
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
Property celsius has no initial value and no initializer, causing error.
Final Answer:
Stored property must have an initial value or be optional. -> Option D
Quick Check:
Stored properties need initial values [OK]
Hint: Stored properties need initial values or init [OK]
Common Mistakes:
Thinking willSet parameter name is invalid
Assuming property observers disallowed in structs
Ignoring missing initial value error
5. You want to track changes to a user's age property and prevent it from being set to a value less than the current age. Which approach using property observers is correct?
hard
A. Use didSet to check if age decreased and reset it back to oldValue.
B. Use willSet to check newValue and revert if less than current age.
C. Use willSet to prevent assignment by throwing an error.
D. Use didSet to print a message but allow any change.
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 A
Quick Check:
didSet can revert changes, willSet cannot prevent them [OK]
Hint: Use didSet to revert invalid changes, willSet can't stop assignment [OK]
Common Mistakes:
Trying to prevent assignment in willSet
Assuming willSet can throw errors
Not resetting property in didSet after invalid change
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.