iterate through caseiterable enum in swift

In Swift, we can iterate through a CaseIterable enum, which is an enum where all cases are known at compile-time and hence conform to the CaseIterable protocol, by using the allCases property.

Here's an example of a simple CaseIterable enum:

main.swift
enum Direction: CaseIterable {
    case north, south, east, west
}
67 chars
4 lines

We can iterate through all the cases in the Direction enum as follows:

main.swift
for direction in Direction.allCases {
    print(direction)
}
61 chars
4 lines

This will output all the cases of the Direction enum, in the order they're defined:

main.swift
north
south
east
west
22 chars
5 lines

Note that if your enum has associated values, you'll need to make sure that they're Equatable and Hashable in order for the enum to be CaseIterable.

gistlibby LogSnag