Value types to reduce sharing
Prefer value types to avoid accidental sharing: structs/enums copy on assignment, helping isolation, predictability, and thread safety.
Why value types?
Swift structs/enums are value types: assignment and passing create copies. This reduces accidental sharing and makes state easier to reason about.
Reference sharing (class)
Classes are reference types: multiple variables can point to the same instance, so mutations leak across aliases.
final class Bag {
var items: [String]
init(_ items: [String]) { self.items = items }
}
let a = Bag(["pen"])
let b = a // REF COPY: a and b refer to the same object
b.items.append("book")
print(a.items) // ["pen","book"] — mutated via b
print(b.items)All lessons in this course
- ARC basics: strong / weak / unowned
- Retain cycles & breaking with weak/unowned
- Value types to reduce sharing