Chris Hannah
My little piece of the internet

Currently Listening

Counting Enum Cases in Swift 4.2

Previous to Swift 4.2, the way you (or at least, I) count the number of cases in an Enum, would be to create an extra case called lastValue, or count. This, of course, was only useful if the raw type was an Int.

enum Option: Int {
    case one
    case two
    case count
}

Option.count.rawValue

Well now, if you make it conform to the CaseIterable protocol, you can use the allCases array. Which is generated automatically, and contains all the cases in the order they were defined.

enum Option: CaseIterable {
    case one
    case two
}

Option.allCases.count

This also means you can not only use it to count the amount of cases, but iterate over all of them much easier.

The allCases value is only generated when the Enum doesn’t use associated values, in which case you will have to do this manually.

enum Option: CaseIterable {
    case one
    case two(Bool)

static var allCases: [Option] = [.one, .two(true)] }