Andre Liberty
Andre Liberty

Reputation: 757

How closure captures value type?

Please look at the following simple example:

var cl: (() -> ())! 
func foo() { 
    var x = 20
    cl = { 
      print(x)
    }

}
foo()
cl() // prints 20

Since x is an Int which is a value type and value types are "living" on the stack, once foo returns x should be vanished. Following the above mentioned line of reasoning x shouldn't exist when cl is called, but it still prints 20. Can somebody explain how closure captures x in this case and keeps it in memory.
Please note that I'm not capturing x with capture list in this case. In case of capture list it is obvious since capturing value type with capture list just makes a copy of a captured value.

Upvotes: 1

Views: 616

Answers (1)

matt
matt

Reputation: 535139

Can somebody explain how closure captures x in this case and keeps it in memory.

There isn't really a "how". That is what a closure is. It does capture x and keep it in memory. Basically, your x does not die when the local reference goes out of scope, because the closure has captured it and lives on; thus x still lives after foo has run, off in an invisible "closure capture" space belonging to this closure, for as long as the closure itself persists.

The ability of closures to do that is what makes a closure a closure.

A feature of this ability that your example doesn't get at is that the captured reference is still writable (because you said var). For example:

var cl: (() -> ())!
func foo() {
    var x = 20
    cl = {
      print(x)
      x += 1
    }

}
foo()
cl() // prints 20
cl() // prints 21

We are thus able to maintain state off in the closure-capture world.

Another thing to notice (I suppose you know this) is that if this had not been an automatic variable that goes out of scope, writing to it would affect the original — the reference is direct. Thus:

var cl: (() -> ())!
var x = 20
func foo() {
    cl = {
      print(x)
      x += 1
    }

}
foo()
cl() // prints 20
cl() // prints 21
print(x) // 22

Upvotes: 4

Related Questions