09th June 2018

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)]
}

Leave a Reply

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Learn More)