Where exactly is this object stored? (Swift)
Both classes and closures are reference types.
var foo = Foo()
creates an object Foo
on the heap and stores a (strong) reference to that object in a local stack variable Foo
.
return { foo }
creates a closure that commits Foo
, so that the closure executes another (strong) reference to that object. On return from the function, the local variable Foo
is out of scope, leaving only one reference from the closure.
var fooGen = foo()
makes a fooGen
reference to the returned closure (which in turn is an object reference Foo
):
fooGen -> closure -> Foo object
Thus, the object Foo
exists if a link exists fooGen
(assuming no additional strong links are created).
Demo:
class Foo
{
deinit {
println("deinit")
}
}
func foo() -> (Void -> Foo)
{
var foo = Foo()
return { foo }
}
if true {
var fooGen = foo()
println("foo")
}
println("done")
Output:
foo deinit done
The object is destroyed when program control leaves the scope fooGen
.
source to share