Enums
Prerequisites: Structs, The switch statement
An enum (enumeration) defines a type with a fixed set of possible values, called cases. Use one whenever a value must be one of a known list of options.
Syntax and example
enum Direction {
case north, south, east, west
}
var heading = Direction.north
heading = .east
switch heading {
case .north: print("Up")
case .south: print("Down")
case .east: print("Right")
case .west: print("Left")
}
print(heading)
Expected output
Right
east
- Once Swift knows the type, you can write just
.east. - The
switchneeds nodefaultbecause it covers every case. If you later addcase up, the compiler flags everyswitchthat doesn't handle it — a huge help when code changes.
Raw values
Cases can carry a fixed raw value of a simple type:
enum Planet: Int {
case mercury = 1, venus, earth, mars
}
enum Status: String {
case active, suspended = "on_hold"
}
print(Planet.earth.rawValue)
print(Status.suspended.rawValue)
print(Planet(rawValue: 4) == .mars)
print(Status(rawValue: "deleted") == nil)
3
on_hold
true
true
Integer raw values count up automatically; string raw values default to
the case name. Planet(rawValue:) is a failable initializer — ideal for
turning stored or received data back into an enum.
Methods, computed properties, and CaseIterable
enum Size: CaseIterable {
case small, medium, large
var price: Double {
switch self {
case .small: 2.5
case .medium: 3.0
case .large: 3.5
}
}
}
for size in Size.allCases {
print("\(size): $\(size.price)")
}
small: $2.5
medium: $3.0
large: $3.5
CaseIterable gives you allCases — every case, in order.
Common mistakes
- Using strings like
"small"for a fixed set of options. A typo in a string is a silent bug; a typo in an enum case is a compile error. - Adding a
defaultto aswitchover your own enum. It hides the compile error you'd otherwise get when a new case is added.