I'm trying to understand how box allocated instance are retained. On the screen here, we
class A {
deinit {
print("deleted")
}
}
var closure: (() -> Void)!
if true {
var aa: A? = A()
closure = {
// Box wraps Optional<A> without creating new variable, it destroyed cuz it follows outer changes to variable
print(aa)
}
aa = nil
}
closure() // output: deleted; nil
That's okey, this is what I expect expect, as i mentioned because -> Box wraps Optional<A>
without creating new variable, it destroyed cuz it
Next example legit too:
class A {
deinit {
print("deleted")
}
}
var closure: (() -> Void)!
if true {
var aa: A? = A()
closure = { [weak aa] in
// creating a weak variable, that ends up when scope is over. That's okay
print(aa)
}
}
closure() // output: deleted; nil
But this example, get me confused a bit
class A {
deinit {
print("deleted")
}
}
var closure: (() -> Void)!
if true {
var aa: A? = A()
closure = {
// Box retains Optional<A> without creating new variable after if scope end, it doesn't destroyed? But why?
print(aa)
}
}
closure() // output: Optional(__lldb_expr_27.A)
Why in last example when scope is over, box allocated instance still gets retained? Is there some implicit copying when scope is over?