0Pricing
Swift Academy · Lesson

Mixed Value/Reference Graphs

Structs containing classes: the hidden reference semantics and how to handle them.

Welcome

Structs can contain classes as stored properties. When they do, the struct behaves as a value type on the outside but shares the class reference internally — a subtle trap.

Struct Containing a Class

```swift class Storage { var data: [Int] = [] } struct Container { var storage = Storage() var label: String = "" } var a = Container() var b = a // copies label, but SHARES storage! a.storage.data.append(1) print(b.storage.data) // [1] — shared! ```

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