Vatsal
Vatsal

Reputation: 18181

Where exactly is this object being stored? (Swift)

Consider the following code:

class Foo
{

}

func foo() -> (Void -> Foo)
{
    var foo = Foo()
    return { foo }
}

var fooGen = foo()

Now whenever I call fooGen, I get my stored Foo instance. But where exactly is foo being stored? Is it inside the stack? And if so, then what is it's lifetime?

Upvotes: 3

Views: 358

Answers (1)

Martin R
Martin R

Reputation: 539705

Both classes and closures are reference types.

var foo = Foo()

creates a Foo object on the heap, and stores a (strong) reference to that object in the local stack variable foo.

return { foo }

creates a closure which captures foo, so that the closure holds another (strong) reference to that object. On return from the function, the local foo variable goes out of scope, to that only one reference from the closure remains.

var fooGen = foo()

makes fooGen a reference to the returned closure (which in turn has a reference to the Foo object):

fooGen -> closure -> Foo object

So the Foo object exists as long as the fooGen reference exists (assuming that no additional strong references 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 of fooGen.

Upvotes: 6

Related Questions