Swift Case Iterable
An enum that adopts CaseIterable gains a list of all its cases. That list is called allCases.
Counting the cases
The Compass enum adopts CaseIterable beside its String raw type. The count of allCases matches the four written cases.
enum Compass: String, CaseIterable {
case north
case south
case east
case west
}
print(Compass.allCases.count)Mapping the cases to raw values
The map call turns each case in allCases into its raw value. The printed array keeps the declaration order of the cases.
enum Compass: String, CaseIterable {
case north
case south
case east
case west
}
let names = Compass.allCases.map { $0.rawValue }
print(names)Looping over every case
The loop walks allCases from the first case to the last case. Each pass prints the raw value of one case.
enum Compass: String, CaseIterable {
case north
case south
case east
case west
}
for direction in Compass.allCases {
print(direction.rawValue)
}Reading one case by position
allCases is a collection, so square brackets read one case by its position. Position 0 holds the first declared case.
enum Size: CaseIterable {
case small
case medium
case large
}
print(Size.allCases[0])
print(Size.allCases.count)Example
enum Season: String, CaseIterable {
case spring
case summer
case autumn
case winter
}
print(Season.allCases.count)
print(Season.allCases.map { $0.rawValue })Key points
- Adopting CaseIterable adds an allCases collection to the enum.
- allCases holds one value for each case the enum declares.
- The cases sit in allCases in declaration order.
- allCases.count gives how many cases the enum declares.
- A loop can walk allCases like any other collection.
In this example, the Season enum adopts CaseIterable and lists four cases. The first print shows the count of allCases, which is 4. The second print maps each case to its raw value and shows the four names in declaration order.
Note
An enum whose cases carry associated values cannot adopt CaseIterable.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
In which order do the cases appear in allCases?