How do I get the count of a Swift enum?
count, enums, swift
Solution
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
- SE-0194 Derived Collection of Enum Cases
Problem
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.)