what is escaping closure

Generated on 8/1/2024

1 search

An escaping closure in Swift is a closure that is allowed to outlive the function it was passed to. This means that the closure can be stored and executed later, even after the function has returned.

When a closure is marked as escaping, the context object that captures the variables must be heap allocated and managed with retains and releases. This is because the closure might be used after the function call completes, so the context needs to persist beyond the function's scope. The context essentially behaves like an instance of an anonymous Swift class.

In contrast, non-escaping closures are guaranteed to be used only within the duration of the function call, allowing their context to be stack allocated, which is more efficient.

For more details, you can refer to the session Explore Swift performance at WWDC 2024.