Why is the result 3? Is this the correct behavior?
func foo()
{
var i = 0 {
willSet {}
}
defer {
i -= 1
print(i) // expected result - 2, prints - 3
}
i = 3
}
Why is the result 3? Is this the correct behavior?
func foo()
{
var i = 0 {
willSet {}
}
defer {
i -= 1
print(i) // expected result - 2, prints - 3
}
i = 3
}
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:
I remove the call to i in willSet:
willSet { print("willSet") } // , i is still", i) }
And get:
Thanks for finding and sharing an interesting example.
For me, it seems to be a bug of Swift. You should better send a bug report to swift.org.
Effectively, exact same problem with didSet.
I tracked in debugger and I observe that willSet does not update i:
func foo() {
var i = 0 {
willSet { print("willSet") }
}
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()
Here is the sequence and values in console:
Statement value in console