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.



Read more here: https://stackoverflow.com/questions/66994702/how-closure-captures-value-type

Content Attribution

This content was originally published by Andre Liberty at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: