Lesson 1 of 9 · 25m
Value Semantics and Swift Data Modeling
Model app data with structs, enums, and immutable boundaries so state stays predictable instead of becoming shared-reference soup.
The first production iOS codebase I inherited had a User class passed through twelve screens. Every screen mutated it, nobody knew which copy was current, and one settings edit changed a profile label by accident. Swift gives you a better default: value semantics. Use it before reaching for architecture diagrams.
Structs are not lesser classes
A struct copy is independent. That single fact removes a whole category of spooky action at a distance:
struct Account: Equatable, Codable, Sendable {
var id: UUID
var displayName: String
var entitlements: Set<Entitlement>
}
var draft = account
draft.displayName = "Renamed locally"
// account.displayName is unchanged.Profiles, line items, settings snapshots, form drafts, filters, and API payload models are natural structs. Network clients, databases, location managers, and authentication sessions are services; reference semantics or actors may fit them better.
Enums are state machines with a compiler attached
Booleans multiply badly. isLoading, hasError, and isEmpty eventually disagree and the UI renders nonsense. Model mutually exclusive states instead:
enum LoadState<Content> {
case idle
case loading
case loaded(Content)
case failed(LocalizedError)
}Impossible combinations cannot exist, and every switch must confront the states a junior developer would otherwise discover during a demo.
Identity deserves deliberate types
String and UUID are easy to pass around and easy to mix up. At trust boundaries, wrappers make the compiler catch swapped identifiers:
struct UserID: Hashable, Codable, Sendable {
let rawValue: UUID
}Do this selectively. Twenty wrapper types for one CRUD screen is architecture theater, but account, tenant, purchase, and document IDs deserve precision.
Mutability should be narrow and visible
Prefer let until mutation is genuinely part of the model. When mutation exists, expose intent rather than public storage:
struct Cart {
private(set) var items: [LineItem] = []
mutating func add(_ item: LineItem) {
if let index = items.firstIndex(of: item) {
items[index].quantity += 1
} else {
items.append(item)
}
}
}The API shows the next developer where invariants live. Directly mutable arrays invite every caller to invent its own rules.
Field notes
- Value types use copy-on-write for many backing stores; cheap logical copies are not zero-cost copies of huge custom buffers.
Codableis a serialization convenience, not proof of a good domain model.Equatablesynthesis becomes questionable when models contain cache tokens or timestamps that are not part of identity.- Reference types are not evil. They become dangerous when ownership is accidental rather than explicit.
Was this lesson helpful?