A delivery can be queued, on its way, or received. Those states need different information: a queued delivery has no tracking details yet, one in transit may have a tracking number and an estimated arrival, and a completed delivery can record who received it. If we keep the state in one property and every possible detail in separate optional properties, we must remember which combinations make sense.
Swift’s enum offers a more direct model. Its cases describe the alternatives, and associated values attach data to the particular case that needs it. The compiler can then help us handle each alternative without pretending that every field is meaningful in every state.
This Molecule explores how to construct and read those values, how they work with the pattern matching from earlier chapters, and where the guarantees stop. The important distinction is between making impossible combinations unrepresentable and validating the data inside a possible case.
A case can carry its own shape
An enum case can be a simple name or a name with one or more typed associated values. Consider this delivery model:
enum Delivery {
case queued
case inTransit(trackingID: String, etaDays: Int)
case delivered(receivedBy: String)
}
func describe(_ delivery: Delivery) -> String {
switch delivery {
case .queued: return "Queued"
case let .inTransit(id, days): return "Tracking \(id): \(days) days"
case let .delivered(name): return "Received by \(name)"
}
}
print(describe(.queued)) // Queued
print(describe(.inTransit(trackingID: "PK-42", etaDays: 2))) // Tracking PK-42: 2 days
print(describe(.delivered(receivedBy: "Mira"))) // Received by Mira
.queued carries no additional information. .inTransit carries two values, a tracking ID and an estimated number of days. .delivered carries the recipient’s name. The three calls show all three shapes: Queued, Tracking PK-42: 2 days, and Received by Mira.
The associated-value labels trackingID, etaDays, and receivedBy make construction readable. Inside the switch, case let .inTransit(id, days) binds the two stored values to local names. They are not global fields of Delivery: they exist as payload only when that case is active. The switch is exhaustive, so each case gets a defined description.
This is different from keeping state, trackingID?, etaDays?, and receivedBy? independently. Such a structure could represent a queued delivery with a recipient or a delivered one without a recipient. The enum model removes those combinations at the level of which fields exist. It does not prove that a tracking string is nonempty or that the estimated days are sensible.
Construct a value, then match its case
Associated values are chosen when you construct an enum value. Two instances of the same case can carry different data. A case is not a fixed constant with a permanently assigned payload.
Sometimes a function needs to handle every case, as describe does. Sometimes it only wants to recognize one. The same associated values work with if case:
enum SearchScope {
case all
case author(id: Int)
case tag(String)
}
let scope: SearchScope = .author(id: 17)
if case let .author(id) = scope {
print("Author: \(id)") // Author: 17
}
let other: SearchScope = .tag("swift")
if case let .author(id) = other {
print("Author: \(id)")
} else {
print("Not an author filter") // Not an author filter
}
scope is .author(id: 17), so the first pattern matches, binds id, and prints Author: 17. other is .tag("swift"), so the author pattern does not match and the else prints Not an author filter. The string "swift" belongs to the tag case; it cannot be read as an author ID.
This is the connection to the earlier pattern-matching Molecules: if case, guard case, and switch are ways to inspect a value’s shape. Associated values define what data each shape can hold. Matching is how we gain access to that data in the appropriate branch.
Different cases can carry different types
The payload does not need to be a string, and cases do not have to agree on one payload type. This is useful when one stage has a fraction and another has a byte count:
enum Download {
case waiting
case progress(Double)
case finished(bytes: Int)
}
func label(_ value: Download) -> String {
switch value {
case .waiting: return "Waiting"
case let .progress(fraction): return "Progress: \(Int(fraction * 100))%"
case let .finished(bytes): return "Finished: \(bytes) bytes"
}
}
print(label(.progress(0.4))) // Progress: 40%
print(label(.finished(bytes: 2048))) // Finished: 2048 bytes
.progress(0.4) holds a Double; the matching branch multiplies it by 100, converts the result to Int, and prints Progress: 40%. .finished(bytes: 2048) holds an Int, so its branch prints Finished: 2048 bytes. The .waiting case carries neither value.
The enum distinguishes a progress measurement from a completed byte count without using an optional Double and optional Int on every value. This makes the model easier to use correctly: the branch that receives fraction knows it matched .progress.
But the type alone does not constrain the number. .progress(1.5) is constructible and would display Progress: 150% with this implementation. That is not a Swift bug; we have not yet modeled the valid range.
Keep the successful path readable
If the rest of a function needs data from one case, guard case can express that requirement before continuing:
enum AccountAccess {
case guest
case member(name: String)
}
func greeting(_ access: AccountAccess) -> String {
guard case let .member(name) = access else {
return "Sign in required"
}
return "Hello, \(name)"
}
print(greeting(.guest)) // Sign in required
print(greeting(.member(name: "Noah"))) // Hello, Noah
For .guest, the pattern fails and greeting returns Sign in required. For .member(name: "Noah"), the pattern matches, binds name, and the function returns Hello, Noah. The bound name is available after the guard, unlike a binding limited to an if branch.
This is useful for a narrow operation that requires a member. It is not a substitute for an exhaustive switch when guests and members need equally important, different processing. The choice depends on whether the function asks one focused question or owns the whole state decision.
Valid shape is not the same as valid data
Associated values rule out some invalid combinations of fields. They do not automatically enforce rules about values inside those fields. A progress percentage, for example, should be within a specific range.
We can put that rule in a small validating type and use the type as the associated value:
struct Percentage {
let value: Int
init?(_ value: Int) {
guard (0...100).contains(value) else { return nil }
self.value = value
}
}
enum Job {
case pending
case running(Percentage)
}
func start(_ amount: Int) -> Job? {
guard let percentage = Percentage(amount) else { return nil }
return .running(percentage)
}
func summary(_ job: Job?) -> String {
guard let job else { return "Invalid progress" }
switch job {
case .pending: return "Pending"
case let .running(progress): return "Running: \(progress.value)%"
}
}
print(summary(start(40))) // Running: 40%
print(summary(start(140))) // Invalid progress
Percentage(40) succeeds, so start(40) returns a .running job containing a valid Percentage; summary prints Running: 40%. Percentage(140) fails because 140 is outside 0...100. Consequently start(140) returns nil, and summary prints Invalid progress.
There are two distinct guarantees. The Job enum says a pending job has no progress payload and a running job has one. The Percentage initializer checks the payload’s range. The optional return from start represents failure to construct a valid running job; it is not a third Job case.
Even this model does not enforce transitions. Code can create a running job without ever creating a pending one. If a workflow must follow a particular sequence, that rule belongs in the API that changes state, not merely in the enum declaration.
When to use another model
Associated values are a strong fit for mutually exclusive alternatives that require different data: navigation destinations, request outcomes, parser results, and stages of an operation. They are less useful when several properties are independent and may coexist. For example, whether a document is pinned and whether it is downloaded can be two separate Boolean properties; forcing those into four enum cases may add complexity rather than remove it.
Do not confuse associated values with raw values. A raw value is defined for a case in the enum declaration and remains the same for that case. An associated value is supplied each time you construct an instance, so .author(id: 17) and .author(id: 23) are both valid values of the same case.
There is also an API-design trade-off. Adding a new case can require callers with exhaustive switches to update their handling. That compiler feedback is often valuable, but it is still a change you must plan for when evolving a public API.
The useful rule is simple: when the kind of value determines which data is meaningful, put that data on the enum case. Then use pattern matching to access it, a validating type for payload invariants, and an explicit state-changing API if transitions matter. Each tool protects a different boundary.
