Add CaseIterable to the enum, then loop over allCases: enum Suit: CaseIterable { case clubs, diamonds, hearts, spades } and for suit in Suit.allCases { print(suit) }. The cases come in the order you declared them, and Suit.allCases.count is the number of cases (4). For an enum with String raw values, suit.rawValue gives the string, which defaults to the case name.
A Swift enum is not a sequence, so for x in Suit { … } doesn't work. Since Swift 4.2 the fix is one word: conform the enum to CaseIterable and the compiler writes a static allCases array for you, with every case in declaration order. That array gives you the loop, the count and everything else an array can do. The sections below cover the basic loop and count, enums with String and Int raw values, turning a string back into a case, stepping to the next or previous case, and enums with associated values, where the compiler refuses and you write allCases yourself. Each example runs on this page: hit Run, then edit the code and run it again.
1CaseIterable and allCasesRecommended
Write CaseIterable after the enum's name and Suit.allCases exists: an array of type [Suit] listing every case. Loop over it with for … in, read its count for the number of cases, and use map, filter, subscripts or enumerated() as with any array. When you add a case later, allCases picks it up on the next build.
// CaseIterable makes the compiler write allCases for you enum Suit: CaseIterable { case clubs, diamonds, hearts, spades } // allCases lists every case in declaration order for suit in Suit.allCases { print(suit) } // The number of cases print("count:", Suit.allCases.count) print(type(of: Suit.allCases)) // It is an ordinary array: index it, map it, filter it print(Suit.allCases[2]) print(Suit.allCases.map { "\($0)" }) let red = Suit.allCases.filter { $0 == .diamonds || $0 == .hearts } print(red) // With the position, as with any array for (i, suit) in Suit.allCases.enumerated() { print(i, suit) }
Output
The loop prints the four cases in the order they are written, and count: 4 answers "how many cases does this enum have". The type prints as Array<Suit>, so Suit.allCases[2] is hearts. One thing to know about printing: a single case prints as its bare name, but a whole array of cases prints each one with its module and type, as in [main.Suit.diamonds, main.Suit.hearts] (main is this program's module). Map the cases to strings first, as the "\($0)" line does, to get ["clubs", …].
2Enums with String and Int raw values
An enum declared as enum Planet: String gives every case a rawValue. Add CaseIterable next to the raw type and the loop works the same way. A case you don't give a string to gets its own name as the raw value. With Int raw values, the first case is 0 and each case after it counts up by one from the case before, so setting one value moves the ones that follow. Printing a case always shows its name; rawValue is the stored value.
// A String raw value defaults to the case name enum Planet: String, CaseIterable { case mercury, venus, earth case mars = "Red Planet" } // print shows the case name; rawValue is the stored string for planet in Planet.allCases { print(planet, "->", planet.rawValue) } // All the raw values as an array of strings let names = Planet.allCases.map(\.rawValue) print(names) // An Int raw value counts up from 0, or from the last one you set enum Level: Int, CaseIterable { case low, medium, high = 10, critical } for level in Level.allCases { print(level.rawValue, level) } // String(reflecting:) adds the module and type, like an array does print(String(reflecting: Planet.earth))
Output
The first three planets have no string of their own, so rawValue equals the case name (earth -> earth), while mars prints as mars -> Red Planet. map(\.rawValue) turns the cases into a plain [String]. In Level, critical follows high = 10 and becomes 11. The order of allCases is always the declaration order, not the raw-value order: sort with sorted { $0.rawValue < $1.rawValue } when you need the other one.
3Find a case from a string
Going the other way, an enum with raw values gets a failable initializer: Size(rawValue: "medium") returns a Size?, which is nil when no case matches. It compares exactly, so Medium with a capital M fails. For case-insensitive input, search allCases with first(where:); the same search works on enums without raw values, by comparing the printed case name. allCases also gives you the list of valid inputs for an error message, and a generic function can take any CaseIterable type.
enum Size: String, CaseIterable { case small, medium, large case extraLarge = "xl" } // Exact raw value: init?(rawValue:) returns Size? print(String(describing: Size(rawValue: "medium"))) print(String(describing: Size(rawValue: "Medium"))) // Case-insensitive: search allCases instead func size(named text: String) -> Size? { Size.allCases.first { $0.rawValue.lowercased() == text.lowercased() } } print(String(describing: size(named: "LARGE"))) print(String(describing: size(named: "XL"))) // Every valid input, for an error message or a menu let input = "huge" if Size(rawValue: input) == nil { let options = Size.allCases.map(\.rawValue).joined(separator: ", ") print("\"\(input)\" is not one of: \(options)") } // No raw value? Match on the printed case name enum Weekday: CaseIterable { case monday, tuesday, wednesday } let day = Weekday.allCases.first { "\($0)" == "tuesday" } print(String(describing: day)) // One generic helper for any CaseIterable enum func caseNames<T: CaseIterable>(of type: T.Type) -> [String] { type.allCases.map { "\($0)" } } print(caseNames(of: Weekday.self)) print(caseNames(of: Size.self))
Output
Size(rawValue: "medium") finds the case and "Medium" gives nil; the allCases search finds LARGE and XL regardless of case. The error line lists the raw values, small, medium, large, xl, so it stays right when you add a size. Note the last line: caseNames prints case names, so it shows extraLarge where the raw value is xl. Unwrap the optional results with if let or guard let, as in How to unwrap an optional.
4Next and previous case, and a case's position
Because allCases is an array, firstIndex(of:) gives a case's position, and the neighboring index gives the next or previous case. Use % to wrap around at the ends, which suits traffic lights, tabs or a theme switcher. Enums without associated values are Equatable automatically, which firstIndex(of:) needs. To compare cases by position, declare the enum Comparable: for an enum without raw values or associated values, the compiler orders the cases as you declared them.
enum Light: CaseIterable, Comparable { case red, green, yellow // The case after this one, wrapping around to the first var next: Light { let all = Light.allCases let i = all.firstIndex(of: self)! return all[(i + 1) % all.count] } // The case before this one, wrapping around to the last var previous: Light { let all = Light.allCases let i = all.firstIndex(of: self)! return all[(i + all.count - 1) % all.count] } } // Step through the cycle var light = Light.red var steps: [String] = [] for _ in 1...5 { steps.append("\(light)") light = light.next } print(steps.joined(separator: " -> ")) print("before red:", Light.red.previous) // The position of a case print(Light.allCases.firstIndex(of: .yellow) ?? -1) // Comparable: cases compare in declaration order print(Light.green < Light.yellow) print([Light.yellow, .red, .green].sorted())
Output
next walks red -> green -> yellow and wraps back to red, and previous of the first case is the last one, yellow. firstIndex(of: .yellow) is 2. The ! after firstIndex(of: self) is safe here because a compiler-written allCases contains every case; if you write allCases by hand and leave a case out, that ! crashes for the missing case. With Comparable, Light.green < Light.yellow is true and sorted() puts the cases back in declaration order.
5Enums with associated values don't get allCases
The compiler can write allCases only when it can list every value, so a case with an associated value, like circle(radius: Double), stops it: there is a different circle for every Double. The program below declares CaseIterable on such an enum and doesn't compile.
enum Shape: CaseIterable { case circle(radius: Double) case square(side: Double) case point } print(Shape.allCases.count)
Output
The build stops with error: type 'Shape' does not conform to protocol 'CaseIterable', a note that the protocol requires property 'allCases' with type '[Shape]', and a second error on the last line, type 'Shape' has no member 'allCases'. The compiler is asking you to supply allCases yourself, which the next section does.
6Write allCases yourself
CaseIterable asks for one thing, a static allCases property, and you can write it. For an enum with associated values, list one sample value per case, or, when the payload is itself a small set, build every combination from other enums' allCases. A hand-written list also lets you leave a case out of the loop, such as a retired status that old data still uses. The cost: when someone adds a case, the compiler won't add it to your list.
enum Shape { case circle(radius: Double) case square(side: Double) case point } // One sample value for each case that has a payload extension Shape: CaseIterable { static var allCases: [Shape] { [.circle(radius: 1), .square(side: 1), .point] } } for shape in Shape.allCases { print(shape) } print("count:", Shape.allCases.count) // When the payload is a small set, list every combination enum Face: CaseIterable { case jack, queen, king } enum Rank: CaseIterable { case number(Int) case face(Face) static var allCases: [Rank] { (2...10).map { .number($0) } + Face.allCases.map { .face($0) } } } print("ranks:", Rank.allCases.count) print(Rank.allCases[0], Rank.allCases[9]) // A hand-picked list can leave a case out of the loop enum Status: String, CaseIterable { case draft, review, published, legacy static var allCases: [Status] { [.draft, .review, .published] } } print(Status.allCases.map(\.rawValue)) print(String(describing: Status(rawValue: "legacy")))
Output
Shape now loops over its three samples, printed with their payloads as circle(radius: 1.0). Rank builds nine number cards and three faces for ranks: 12, and a nested case prints its inner enum in full, as face(main.Face.jack). Status loops over three cases while legacy still exists: Status(rawValue: "legacy") finds it. That is also the catch with a hand-written list: .legacy is not in allCases, so a next property like the one in section 4 stops on it with Fatal error: Unexpectedly found nil while unwrapping an Optional value.
7Which should you use?
| Method | Gives you | Stays in sync | Best for |
|---|---|---|---|
| for c in E.allCases | Every case, in order | Yes, compiler-written | Looping over any simple enum |
| E.allCases.count | Number of cases | Yes | Counting the cases of an enum |
| E.allCases.map(\.rawValue) | The raw values | Yes | String or Int enums, menus, error messages |
| E(rawValue: s) | An optional case | Yes | Exact string or number back to a case |
| allCases.firstIndex(of:) | A position | Yes | Next and previous case, cycling |
| static var allCases: [E] | The list you write | No, update it by hand | Associated values, leaving a case out |
Frequently asked questions
How do I get the count of a Swift enum?
Conform the enum to CaseIterable and read allCases.count: for enum Suit: CaseIterable { case clubs, diamonds, hearts, spades }, Suit.allCases.count is 4. Old answers from before Swift 4.2 keep a static let count constant or count up through Int raw values until init?(rawValue:) returns nil; both work only in special cases or go stale when a case is added.
How do I enumerate an enum with String raw values?
Add CaseIterable next to the raw type, enum Planet: String, CaseIterable, and loop over Planet.allCases. Inside the loop, planet prints as the case name and planet.rawValue is the string. A case without an explicit string has its own name as the raw value, so Planet.earth.rawValue is "earth". Planet.allCases.map(\.rawValue) gives all the strings as an array.
In what order does allCases list the cases?
In the order you declared them, even when the raw values are in a different order. For enum Priority: Int, CaseIterable { case high = 3, low = 1, medium = 2 }, allCases.map(\.rawValue) is [3, 1, 2]. To loop in raw-value order, sort first: Priority.allCases.sorted { $0.rawValue < $1.rawValue }.
Why does my enum say it does not conform to protocol CaseIterable?
Because at least one case has an associated value, so there is no finite list of values to generate. The compiler reports "type 'Shape' does not conform to protocol 'CaseIterable'". Write static var allCases: [Shape] yourself with one sample value per case, or build every combination when the payload is another CaseIterable enum.
Why does printing an array of cases show main.Suit.hearts?
A single case prints as its bare name, hearts, but an array prints each element with its full name: module (main for a single-file program), type, then case. Map to strings first, Suit.allCases.map { "\($0)" }, or to raw values with map(\.rawValue), to print ["clubs", "diamonds", "hearts", "spades"].
How do I pick a random case of an enum?
Call randomElement() on allCases: Suit.allCases.randomElement()!. It returns an optional because an array can be empty; the ! is safe for an enum that has at least one case. Use shuffled() on allCases to get every case in random order.