I met a similar question in Swift Memory Management: Storing func in var but that didn't solve my problem.
Here is my class definition:
class Test {
var block: (() -> Int)?
func returnInt() -> Int {
return 1
}
deinit {
print("Test deinit")
}
}
I tried two ways to assign value to block
property and got completely different result. The second approach didn't cause retain circle, which is quite unexpected:
var t = Test()
// This will lead to retain cycle
// t.block = t.returnInt
// I thought this will also lead to retain cycle but actually didn't
t.block = {
return t.returnInt()
}
t = Test()
In my opinion, variable t
is captured by block
while block
is a property of t
, so can anyone explain why there isn't a retain cycle?