How do closures work (memory management)

Closures are actually conceptually a bit more like this:

struct Closure {
    var functionPointer: UnsafeRawPointer
    var closureContext: AnyObject?
}

That is, they are two pointers wide, where the first pointer is a function pointer pointing to the code that implements the closure, and the second pointer optionally points to a reference counted object containing the closed-over state.

So, yes, the capture list is heap allocated, and it is reference counted. However, I don’t think it is an actual Swift object per se, it behaves somewhat more unusually than that. I’m afraid I can’t help more than this.

12 Likes