How do I get the count of a Swift enum?

Robert Atkins picture Robert Atkins · Nov 23, 2014 · Viewed 62.1k times · Source

How can I determine the number of cases in a Swift enum?

(I would like to avoid manually enumerating through all the values, or using the old "enum_count trick" if possible.)

Answer

Martin R picture Martin R · May 4, 2018

As of Swift 4.2 (Xcode 10) you can declare conformance to the CaseIterable protocol, this works for all enumerations without associated values:

enum Stuff: CaseIterable {
    case first
    case second
    case third
    case forth
}

The number of cases is now simply obtained with

print(Stuff.allCases.count) // 4

For more information, see