Enums and associated values
Enums and associated values
A score can be pending or recorded. Encoding those states as unrelated strings and numbers allows inconsistent combinations. An enum declares a defined set of cases, and associated values carry data belonging to a particular case.
What you’ll learn
- Model mutually exclusive states with an enum.
- Extract an associated score in an exhaustive switch.
Enums and associated values in the example
Defined cases
A score can be pending or recorded.
Defined casesRecorded value 80
Unlike a raw value, which gives a case a fixed underlying representation, an associated value is supplied for a particular instance.
Recorded value 80Match and extract
The recorded instance carries 80.
Match and extract
How enums and associated values works
Unlike a raw value, which gives a case a fixed underlying representation, an associated value is supplied for a particular instance. A switch can match the case and extract that instance’s value. Covering every enum case makes missing state handling a compile-time concern.
Work through enums and associated values
Save this complete program as main.swift and run it with the Swift toolchain. No separate input file is needed.
Swift · complete program
enum Result {
case pending
case recorded(Int)
}
let result = Result.recorded(80)
switch result {
case .pending: print("Awaiting result")
case .recorded(let score): print("Score:", score)
}Expected output
Score: 80Follow the execution
The recorded instance carries 80. Matching that case binds score inside the branch and prints it. There is no separate “pending” flag that could accidentally coexist with a recorded score.
Try this program in the Swift compiler. Paste the complete source above.
Practice: Enums and associated values
Your task: What would Result.pending carry?
Swift · complete program
enum Result {
case pending
case recorded(Int)
}
let result = Result.recorded(80)
switch result {
case .pending: print("Awaiting result")
case .recorded(let score): print("Score:", score)
}Worked answer
It carries no score because that case declares no associated value. The matching branch can show an absence message without inventing a number.
Keep alternatives internally consistent
Use enums for meaningful alternatives, not just to hide strings. Adding a case may require updating exhaustive switches. Raw-value initialization can fail for an unknown value and therefore often returns an optional.
Check your decision
Keep alternatives internally consistent
It carries no score because that case declares no associated value. The matching branch can show an absence message without inventing a number. Use enums for meaningful alternatives, not just to hide strings.
Further reading: official Swift language guide.
Reaching the recap and completing the quizzes are separate milestones.