why consuming and borrowing can be applied only to escaping closures?

Generated on 8/9/2024

1 search

Consuming and borrowing can be applied only to escaping closures because of the way Swift manages the lifetime and memory of captured variables in closures.

For non-escaping closures, the closure is guaranteed to be used only within the duration of the call, so the context can be allocated on the stack, and the address of that will be passed to the function. This allows for efficient memory management and ensures that the variable's lifetime is tightly controlled.

However, for escaping closures, the closure can outlive the function call, meaning the context object must be heap allocated and managed with retains and releases. This is because the closure might be used at any point in the future, and Swift needs to ensure that the captured variables remain valid for the entire lifetime of the closure. This is why consuming and borrowing, which involve transferring or temporarily taking ownership of a value, are only applicable to escaping closures. The context essentially behaves like an instance of an anonymous Swift class, and Swift needs to manage the memory and lifetime of these captured variables carefully.

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