My understanding for closure was, it will capture all directly referenced objects strongly irrespective of whether the object variable was declared weak
or strong
outside the closure and, if we want to capture them weakly, then we need to explicitly define a capture list and mark them weak
in that capture list.
obj?.callback = { [weak obj] in
obj?.perform()
}
However in my test, I found that if the variable is already weak
outside the closure, then we don't need to use capture list to capture it weakly.
class Foo {
var callback: (() -> ())?
init() {
weak var weakSelf = self
callback = {
weakSelf?.perform()
}
// is above equivalent to below in terms of memory management?
// callback = { [weak self] in
// self?.perform()
// }
}
func perform() {
print("perform")
}
deinit {
print("deinit")
}
}
let foo = Foo() // prints "deinit foo"
The above snippet is not creating any retain cycle. Does this mean we don't need to explicitly capture an object variable weakly in capture list if the variable is already declared weak
and capture list just provides syntactical advantage over creating a weak
variable before using them inside closure.