Predict the output
What does this print?
struct Box {
var value = 0 {
willSet { print("will \(newValue)") }
didSet { print("did \(oldValue)") }
}
init() { value = 1 }
}
var b = Box()
b.value = 2Hint 1 of 1
Do observers fire inside init?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: B will 2, did 1
Correct. Only the assignment after init triggers the observers.
Why not the others?
- A will 1, did 0, will 2, did 1. Observers don't run when the type's own initializer sets the property.
- C did 1. willSet runs too, before the change.
- D Nothing. Assignments outside init do trigger observers.