Swift Enums
An enum is a type with a fixed list of cases. A value of the type can hold one case from that list at a time.
One case from the list
The Direction enum lists four cases, and the heading holds the north case. The test confirms which case it holds.
enum Direction {
case north
case south
case east
case west
}
let heading = Direction.north
print(heading == Direction.north)String raw values
This Direction enum is based on String, so each raw value matches its case name. Both raw values print as plain text.
enum Direction: String {
case north
case south
case east
case west
}
print(Direction.north.rawValue)
print(Direction.south.rawValue)Int raw values from a chosen start
The Level enum starts its count at 5 for the low case. The cases after it count up to 6 and 7 on their own.
enum Level: Int {
case low = 5
case medium
case high
}
print(Level.low.rawValue)
print(Level.medium.rawValue)
print(Level.high.rawValue)A switch over every case
The switch lists all four Direction cases, so it covers the value with no default branch. The east branch runs for this heading.
enum Direction {
case north
case south
case east
case west
}
let heading = Direction.east
switch heading {
case .north:
print("Going north")
case .south:
print("Going south")
case .east:
print("Going east")
case .west:
print("Going west")
}A case carrying a value
The score case carries an Int with it, and the switch binds that number to the name points. The print shows the carried number 42.
enum Result {
case score(Int)
case fail
}
let result = Result.score(42)
switch result {
case .score(let points):
print(points)
case .fail:
print("No score")
}Example
enum Season: String {
case spring
case summer
case autumn
case winter
}
let season = Season.summer
print(season.rawValue)
switch season {
case .spring:
print("Mild")
case .summer:
print("Hot")
case .autumn:
print("Cool")
case .winter:
print("Cold")
}Key points
- An enum is a type with a fixed list of cases.
- A case is read by writing the type name, a dot, and the case name.
- An enum based on String gives each case a raw value with the same text as the case name.
- An enum based on Int counts up from the first raw value it is given.
- A switch over an enum value must cover every case, so it needs no default branch.
- A case can carry an associated value, which is extra data stored with that case.
- The rawValue property reads the raw value of a case.
In this example, the Season enum is based on String and lists four cases. The season holds the summer case, so the first print shows its raw value summer. The switch then covers all four cases, and the summer branch prints Hot.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
What does Direction.north.rawValue print when Direction is based on String?