Intermediate 22 min readModule: Module 3: Value Types vs Reference Types (Structs, Enums, Classes)
Value Types vs Reference Types & Copy-on-Write (COW)
Understand the core architectural difference between Value Types (Structs, Enums) and Reference Types (Classes), heap vs stack allocations, and Copy-on-Write optimization.
What You Will Learn in This Lesson
- The difference between Value Semantics (copied on assignment) and Reference Semantics (shared pointers)
- Stack memory allocation (fast, automatic) vs Heap memory allocation (dynamic, ARC overhead)
- Enums with Associated Values for rich domain state modeling
- How Swift standard collections (Array, Dictionary) implement Copy-on-Write (COW) for high performance
Introduction & Core Concept
One of Swift's defining architectural characteristics is its strong preference for Value Types (Structs and Enums) over Reference Types (Classes). When you pass a value type to a function or assign it to a new variable, it is copied independently, ensuring that modifying one instance can never unexpectedly alter another instance.
WHY DOES THIS MATTER IN THE REAL WORLD?
Unintended shared mutable state is the primary cause of bugs in multithreaded programming. By defaulting to structs and value semantics, Swift applications are inherently thread-safe and easier to reason about.
Syntax & Structure
swift
struct Point { var x: Double; var y: Double }class Node { var value: Int; init(value: Int) { self.value = value } }Demonstrating Value Semantics vs Reference Semantics
swiftswift
123456789101112131415161718192021222324252627282930313233343536// Value Types (Structs) vs Reference Types (Classes)import Foundation// 1. Value Type: Struct (Copied on assignment)struct DocumentConfig {var title: Stringvar wordCount: Int}// 2. Reference Type: Class (Shared pointer on heap)class SharedSession {var sessionId: Stringinit(sessionId: String) { self.sessionId = sessionId }}func demonstrateSemantics() {// Value Type Behavior:var doc1 = DocumentConfig(title: "Architecture Guide", wordCount: 1500)var doc2 = doc1 // Deep copy is made!doc2.title = "Updated Title"print("=== Value Types (Structs) ===")print("doc1.title: \(doc1.title)") // Unchanged: "Architecture Guide"print("doc2.title: \(doc2.title)") // Modified: "Updated Title"// Reference Type Behavior:let session1 = SharedSession(sessionId: "sess_original")let session2 = session1 // Copies the POINTER, not the instance!session2.sessionId = "sess_MUTATED"print("\n=== Reference Types (Classes) ===")print("session1.sessionId: \(session1.sessionId)") // Mutated: "sess_MUTATED"print("session2.sessionId: \(session2.sessionId)") // Mutated: "sess_MUTATED"}demonstrateSemantics()
Line-by-Line Technical Breakdown
1Copy-on-Write (COW): To avoid expensive memory copies when passing large arrays or dictionaries, Swift uses Copy-on-Write. The underlying memory buffer is shared read-only among copies until one of the copies attempts to mutate its contents—at which point Swift creates a private copy of the data buffer.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[SWIFT]
SWIFT SOURCE EDITOR
Interactive Live CodeCommon Mistakes & How to Avoid Them
#1: Using classes by default for simple domain models, introducing unnecessary heap allocations and reference sharing.
Default to structs in Swift. Only use classes when reference identity (===) or inheritance is explicitly required.
Incorrect / Antipattern
class User { var name: String; init(name: String) { self.name = name } }Correct / Professional Solution
struct User { var name: String }Industry Best Practices & Professional Standards
- Default to `struct` for all data models, DTOs, and view configurations.
- Use `enum` with associated values to model finite state machines and network results.
- Reserve `class` for reference-identity requirements (e.g. shared state controllers or file handles).
Lesson Summary & Core Takeaways
- Structs and Enums are Value Types allocated on the stack with independent copy semantics.
- Classes are Reference Types allocated on the heap with shared pointer semantics.
- Copy-on-Write (COW) optimizes Swift collection copies for peak performance.