function - Where exactly is this object being stored? (Swift) -
consider following code:
class foo { } func foo() -> (void -> foo) { var foo = foo() return { foo } } var foogen = foo()
now whenever call foogen
, stored foo
instance. foo
being stored? inside stack? , if so, it's lifetime?
both classes , closures reference types.
var foo = foo()
creates foo
object on heap, , stores (strong) reference object in local stack variable foo
.
return { foo }
creates closure captures foo
, closure holds (strong) reference object. on return function, local foo
variable goes out of scope, 1 reference closure remains.
var foogen = foo()
makes foogen
reference returned closure (which in turn has reference foo
object):
foogen -> closure -> foo object
so foo
object exists long foogen
reference exists (assuming no additional strong references 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 destroyed when program control leaves scope of foogen
.
Comments
Post a Comment