Where exactly is this object stored? (Swift)

Consider the following code:

class Foo
{

}

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

var fooGen = foo()

      

Now when I call fooGen

I get my saved instance Foo

. But where exactly is it stored Foo

? Is it inside the stack? And if so, what kind of life is it?

+3


source to share


1 answer


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

.

+4


source







All Articles