when the reference type is stored on the stack

Generated on 2/25/2025

1 search

In the context of Swift and memory management, reference types are typically stored on the heap rather than the stack. Reference types, such as classes, involve pointers to objects that are allocated on the heap. When you copy a reference type, you are copying the reference (or pointer) to the object, not the object itself. This is known as a shallow copy.

However, there are scenarios where the context containing captured values in closures can be allocated on the stack, particularly for non-escaping closures. In these cases, the address of the context is passed around, allowing for efficient memory usage. For escaping closures, the context must be heap-allocated because the closure might outlive the function call in which it was created.

For more detailed information on how Swift handles memory allocation and the differences between stack and heap storage, you can refer to the session Explore Swift performance (08:29).