How are Swift’s closures implemented on the runtime stack? I imagine non-escaping closures are just sent with an extra access link to the stack frame it encloses, but how do escaping closures work? Where is its enclosed activation record maintained?
Asked
Active
Viewed 393 times
2
-
escaping closures with captured variables are stored as memory managed boxes on the heap (using ARC). In fact, all closures start like this, until the optimizer does a pass which promotes it to the stack, when possible to do so. – Alexander May 03 '17 at 04:20
-
@Alexander , if the variables live in the heap, how are they accessed by the original function they live in? Or does Swift automatically convert every variable that lives a function that contains a closure to heap variables? – taylor swift May 03 '17 at 04:23
-
http://stackoverflow.com/questions/41256612/how-are-escaping-closures-implemented-in-swift-3-under-the-hood-are-they-impl – matt May 03 '17 at 04:24
-
1@taylorswift Yep, the local variables are moved to the heap whenever there's a closure that will need to capture them and box them on the heap, so that they can outlive the stack frame of the function they were allocated in – Alexander May 03 '17 at 04:26
-
1See e.g. https://developer.apple.com/videos/play/wwdc2011/308/ at around the 37 minute mark – Scott Thompson May 03 '17 at 04:52
-
Also https://developer.apple.com/videos/play/wwdc2012/712/ at 23:22 – Scott Thompson May 03 '17 at 05:47
-
Also relevant: [Swift function object wrapper in apple/swift](http://stackoverflow.com/q/43171341/2976878) – Hamish May 03 '17 at 09:20