#32: List All Enum Cases in Swift 5

If an enum has no associated values, conforming to CaseIterable gives you an allCases collection automatically:

enum Direction: CaseIterable {
    case north, south, east, west
}

Direction.allCases

That is the modern replacement for manually maintaining arrays of cases.

for direction in Direction.allCases {
    print(direction)
}

For enums with associated values, you still need to build your own list because Swift cannot infer all possible combinations.


I'm also on Twitter and GitHub.

Subscribe via RSS.