Swift Enums
An enumeration (enum) defines a type with a fixed set of possible values called cases. Enums make impossible states impossible: a traffic light can be red, yellow or green, and nothing else. Swift enums are far more powerful than in most languages — they can carry data, have methods and conform to protocols.
Defining an enum
Use the enum keyword and list the cases with case. By convention, type names start with an uppercase letter and case names with a lowercase letter.
enum Direction {
case north
case south
case east, west // several cases on one line
}
var heading = Direction.north
print(heading)
heading = .west // the type is already known, so the dot is enough
print(heading)north
west
Once Swift knows a variable has type Direction, you can use the short dot syntax (.west) instead of writing the full Direction.west.
Enums and switch
A switch over an enum must be exhaustive — it has to handle every case. That is a safety feature: if you add a new case later, the compiler points you to every switch that needs updating.
enum TrafficLight {
case red, yellow, green
}
func advice(for light: TrafficLight) -> String {
switch light {
case .red: return "Stop"
case .yellow: return "Slow down"
case .green: return "Go"
}
}
for light in [TrafficLight.green, .yellow, .red] {
print("\(light): \(advice(for: light))")
}green: Go
yellow: Slow down
red: Stop
Raw values
An enum can give every case a raw value of the same type (Int, String, Double, Character). For Int, Swift numbers the cases automatically starting from the first value; for String, the default raw value is the case name.
enum Planet: Int {
case mercury = 1, venus, earth, mars
}
enum Suit: String {
case hearts = "♥", spades = "♠"
case clubs // raw value is "clubs"
}
print(Planet.earth.rawValue)
print(Suit.hearts.rawValue, Suit.clubs.rawValue)
// The failable initializer returns an optional
if let p = Planet(rawValue: 4) {
print("Planet 4 is \(p)")
}
print(Planet(rawValue: 9) == nil)3
♥ clubs
Planet 4 is mars
true
Planet(rawValue:) returns Planet? because not every number matches a case.
Associated values
Raw values are fixed per case. Associated values are different: each instance of a case stores its own data, and each case can store different kinds of data.
enum Payment {
case cash
case card(number: String, expiry: String)
case voucher(code: String, amount: Double)
}
func describe(_ p: Payment) -> String {
switch p {
case .cash:
return "Paid in cash"
case .card(let number, _):
return "Card ending in \(number.suffix(4))"
case let .voucher(code, amount) where amount >= 50:
return "Big voucher \(code) worth \(amount)"
case .voucher(let code, _):
return "Voucher \(code)"
}
}
let payments: [Payment] = [
.cash,
.card(number: "4111222233334444", expiry: "12/28"),
.voucher(code: "SPRING", amount: 75),
.voucher(code: "TEN", amount: 10),
]
for p in payments { print(describe(p)) }Paid in cash
Card ending in 4444
Big voucher SPRING worth 75.0
Voucher TEN
Use let inside the pattern to pull the values out. case let .voucher(code, amount) is a shorthand that binds every value as a constant, and a where clause adds an extra condition.
Tip: Swift's own
Optionaltype is just an enum with two cases:.noneand.some(Wrapped)— an associated value!
Methods, computed properties and CaseIterable
Enums can have methods and computed properties. Adopting the CaseIterable protocol gives you an allCases array for free.
enum Coffee: CaseIterable {
case espresso, latte, mocha
var price: Double {
switch self {
case .espresso: return 2.5
case .latte: return 3.8
case .mocha: return 4.2
}
}
func label() -> String {
"\(self) – $\(price)"
}
}
print("Menu has \(Coffee.allCases.count) drinks")
for drink in Coffee.allCases {
print(drink.label())
}Menu has 3 drinks
espresso – $2.5
latte – $3.8
mocha – $4.2
Inside an enum, self is the current case. A method that changes self (for example next() on a light) must be marked mutating.
Raw values vs associated values
| Raw values | Associated values | |
|---|---|---|
| Declared | enum E: Int { case a = 1 } |
case a(Int) |
| Same for every instance? | Yes, fixed per case | No, set when the value is created |
| Types | One type for all cases | Each case can differ |
| Create from data | E(rawValue: 1) |
.a(42) |
Note: An enum cannot have both raw values and associated values at the same time.
Test yourself
What does Planet(rawValue: 9) return when no case has raw value 9?
- A crash
0nil- The first case
Which feature lets each instance of a case store its own data?
- Raw values
- Associated values
- CaseIterable
- Computed properties
Why must a switch over an enum be exhaustive?
- For performance
- So the compiler can guarantee every case is handled
- Because enums cannot have a default
- It does not have to be