I changed by adding a statement in willSet:
func foo() {
var i = 0 {
willSet { print("willSet", i) }
}
defer {
i -= 1
print("defer", i) // expected result - 2, prints - 3
}
i = 3
}
foo()
And get the expected result
willSet 0
willSet 3
defer 2
I instrumented more:
func foo() {
var i = 0 {
willSet { print("willSet, i is still", i) }
}
defer {
i -= 1
print("defer", i) // expected result - 2, prints - 3
}
print("soon i = 3, now is", i)
i = 3
print("now i = 3", i)
}
foo()
And get:
soon i = 3, now is 0
willSet, i is still 0
now i = 3 3
willSet, i is still 3
defer 2
I remove the call to i in willSet:
willSet { print("willSet") } // , i is still", i) }
And get:
soon i = 3, now is 0
willSet
now i = 3 3
willSet
defer 3