SWIFT / CHAPTER 09
Associated values and exhaustive state
IntermediateRepresent meaningful alternatives with the data each requires.
By the end of this chapter
- Model alternatives using enum cases
- Extract associated values with switch
- Avoid inconsistent flag combinations
The idea
An enum can represent a closed set of states, and each case can carry associated values relevant to that state. A load result might be success with a count or failure with a message. This is more precise than keeping several independent booleans and optional fields whose combinations may contradict each other. Construction selects one case with its corresponding data.
A switch over an enum must handle the possible cases, making missing decisions visible to the compiler. Bind associated values in the matching case rather than force unwrapping unrelated storage. A default branch can be appropriate, but it can also hide the need to reconsider behavior when the model changes. Choose explicit cases when each alternative requires a distinct user-visible response or state transition.
enum Load {case success(Int);case failure(String)}
func message(_ result:Load)->String {switch result {case .success(let n):return "Loaded \(n)";case .failure(let reason):return reason}}
print(message(.success(3)))Loaded 3
The success case carries the count directly, and pattern matching makes that value available only in the matching branch.
Try it yourself
Model a payment as pending, accepted with a receipt ID, or rejected with a reason.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING