Understanding Value vs Reference Semantics in Swift

One of the most important (and subtle) ideas in Swift is how data is passed around: value types vs reference types.

Structs and enums are value types

Classes are reference types

The Core Difference

With a value type, assigning or passing it creates a copy.

struct User {
var name: String
}

var a = User(name: "John")
var b = a
b.name = "Mike"

print(a.name) // John

a stays unchanged because b is a copy.

With a reference type, multiple variables point to the same instance.

class User {
var name: String
init(name: String) {
self.name = name
}
}

var a = User(name: "John")
var b = a
b.name = "Mike"

print(a.name) // Mike

Now a changes because both refer to the same object.

Why It Matters

Structs (value types) → safer, predictable, easier to reason about

Classes (reference types) → shared mutable state, more flexible but riskier

Rule of Thumb

Use structs by default.
Reach for classes only when you need shared state or identity.

This distinction drives much of Swift’s design--especially in SwiftUI and Swift’s concurrency model.