I tested the quick close of the Xcode playground.
This is my code:
import UIKit class A{ var closure: ()->() = {} var name: String = "A" init() { self.closure = { self.name = self.name + " Plus" } } deinit { print(name + " is deinit") } } var a: A? a = A() a = nil
As expected, a is closed closed, so a is never released.
But, when I add this line to the last line:
a?.closure = { a?.name = "ttt" }
Then I found that "A is deinit" in the output window, which means that a is freed. What for? is not a recycle reference?
To be a test, I use a function to set a closure whose code is version 2:
import UIKit class A{ var closure: ()->() = {} func funcToSetClosure(){ self.closure = { self.name = "BBB"} } var name: String = "A" init() { self.closure = { self.name = self.name + " Plus" } } deinit { print(name + " is deinit") } } var a: A? a = A() a?.funcToSetClosure() a = nil
Again, a is never released.
So, I came to the conclusion that when the closure is set by init or by a function in the class, it will cause a recycle reference, when it is inserted towards the class, it will not cause a recycle reference. I'm right?
source share