Last Run on XCODE 11.6 / Swift 5.2

Definition

CaseIterable is a protocol in Swift, that typically lets an enumeration to provide all of its cases as a collection.

Lets look at a simple example from my RoadRage car game. This is an enum type called TrafficType listing the cases of traffic/obstacle Sprites generated in my RoadRage car game.

enum TrafficType: UInt32 {
    case Police
    case Ambulance
    case FireTruck
    case Van
    case SportsCar
    case Taxi
}

In my game I would like to find out the total count of the TrafficType entities. I would also like the ability to randomly pick a traffic object from the list to keep generating obstacles during the game loop. And to achive that is as simple as conforming to the CaseIterable protocol in the enum.

Conforming to CaseIterable

enum TrafficType: UInt32, CaseIterable {
    case Police
    case Ambulance
    case FireTruck
    case Van
    case SportsCar
    case Taxi
}

As you can see, it was as simple as adding the keyword “CaseIterable” to the enum. The swift compiler will automatically synthesize all the cases in an appropriately named collections variable “allCases”.

// Total Traffic Type Entities
print("\(TrafficType.allCases.count)")

// Traffic Entity at a specific index.
print("\(TrafficType.allCases[3])")

// Iterating through each of the TrafficType entities.
for traffic in TrafficType.allCases {
    print("\(traffic)")
}