how reference type is captured in a closure?

Generated on 8/9/2024

1 search

In Swift, when you refer to a local variable in a closure, you capture that variable by reference. This allows you to make changes to the variable that will be observed in the original scope, and vice versa.

For non-escaping closures, this doesn't change the lifetime of the variable. The closures can handle this by just capturing a pointer to the variable's allocation. However, if the variable is captured by an escaping closure, the lifetime of the variable can be extended for as long as the closure is alive. As a result, the variable also has to be heap allocated, and the closure context has to retain a reference to that object.

For more details, you can refer to the session Explore Swift performance (28:11).