0Pricing
Swift Academy · Lesson

Stack vs Heap: Where Values Live

How structs live on the stack and classes on the heap, and the performance implications.

Stack vs Heap: Where Values Live is a free Swift Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Welcome

Understanding where Swift values live in memory — the stack vs the heap — is essential for writing performant, predictable code.

The Stack

The stack is a contiguous block of memory managed automatically: • Function locals and parameters live here • Allocation is O(1) — just move a pointer • Automatically freed when the scope exits • Thread-local — each thread has its own stack

The Heap

The heap is a shared pool for long-lived allocations: • Objects live here when their lifetime extends beyond one scope • Allocation requires finding free memory — more expensive • Managed by ARC for classes • Shared across threads — requires synchronisation

Structs Live on the Stack

```swift func compute() { var pt = CGPoint(x: 3, y: 4) // on the stack pt.x += 1 } // pt freed automatically ``` Small structs are passed by copy — zero heap overhead.

Classes Live on the Heap

```swift class Dog { var name: String init(name: String) { self.name = name } } var d = Dog(name: "Rex") // Dog instance on heap // 'd' is a pointer on the stack ```

Large Structs May Use the Heap

Large structs (arrays, strings, large value types) use COW and heap storage internally even though they behave as value types: ```swift var arr = [Int](repeating: 0, count: 10_000) // The array's buffer is on the heap; 'arr' itself is a stack value ```

Capture in Closures

When a closure captures a value-type variable that must outlive the scope, Swift boxes it on the heap: ```swift var count = 0 let increment = { count += 1 } // count captured in a heap box increment() print(count) // 1 ```

Protocol Existential Boxing

Storing small value types in `any Protocol` variables can cause heap allocation (existential boxing): ```swift var shape: any Shape = Circle(radius: 5) // may allocate on heap ``` Small types (≤3 words) are inlined; larger types are boxed.

Measuring Allocations

Use Instruments Allocations template to see heap allocations: 1. Profile > Allocations 2. Filter by class or category 3. Track `alloc` vs `dealloc` counts High alloc counts in loops often indicate unexpected boxing.

Design Implications

• Prefer structs for short-lived data-holding types — stack speed • Use classes when identity or shared state is needed • Avoid allocating in tight loops — pre-allocate with `reserveCapacity` • Profile before optimising — premature optimisation wastes time

Quick Check

Which type of memory is automatically freed when a function scope exits?

Recap

Key takeaways: • Stack: cheap, automatic, thread-local, value types • Heap: flexible, ARC-managed, reference types • Large structs use internal heap buffers (COW) • Closures that capture variables box them on the heap • Use Instruments Allocations to detect unexpected heap pressure Next: mutation, sharing, and unexpected aliasing.

Frequently asked questions

Is the “Stack vs Heap: Where Values Live” lesson free?

Yes — the full text of “Stack vs Heap: Where Values Live” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Stack vs Heap: Where Values Live”?

How structs live on the stack and classes on the heap, and the performance implications. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Stack vs Heap: Where Values Live” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Stack vs Heap: Where Values Live
  2. Mutation, Sharing and Unexpected Aliasing
  3. Mixed Value/Reference Graphs
  4. Designing APIs for Value Semantics
← Back to Swift Academy