As far as I know and as mentioned in this thread, if I set a property value in its didSet
observer, it should not trigger the observer again. OK, then I wrote a piece of code like this:
class B {
var i = 0 {
didSet {
print("didSet called")
self.i += 1
}
}
}
var y = B()
y.i = 2
print(y.i)
This code prints "didSet called"
and 3
as output as expected. But I made a small change to this code as follows:
class B {
var i = 0 {
didSet {
print("didSet called")
doit(val: self)
}
}
func doit(val: B) {
val.i += 1
}
}
var y = B()
y.i = 2
print(y.i)
But now it falls into an infinite loop printing "didSet called"
. Why if I set a value to the variable inside didSet
via passing it through a function argument, does it trigger didSet
again? Since the passed object should refer to the same object, I don't know why this happens. I tested and if I set it via a closure in didSet
rather than a normal function it goes to an infinite loop again.
Update: It is funny that even this triggers an infinite loop:
class B {
var i = 0 {
didSet {
print("called")
doit()
}
}
func doit() {
self.i += 1
}
}