← Back to Swift Course | Chapter 10: Enums | Lesson 4 of 6

CaseIterable

CaseIterable is a magic label you put on an enum so Swift will hand you back a list of every single option it has.
Syntax
swift
enum EnumName: CaseIterable {
    case first, second, third
}

for item in EnumName.allCases { }
EnumName.allCases.count

Adopting CaseIterable

Adding CaseIterable conformance to an enum automatically synthesizes an .allCases static property listing every case.

Example: Adopting CaseIterable

markup
// Define an enum `Direction` listing its possible cases
enum Direction: CaseIterable {
    // Enum case(s): `north, south, east, west`
    case north, south, east, west
}
// Loop over `Direction.allCases`, binding each item to `direction`
for direction in Direction.allCases {
    // Print `direction` to the console
    print(direction)
}

Counting Cases

.allCases.count gives the total number of cases without needing to manually count or maintain a separate list.

Example: Counting Cases

markup
// Define an enum `Direction` listing its possible cases
enum Direction: CaseIterable {
    // Enum case(s): `north, south, east, west`
    case north, south, east, west
}
// Print "Total directions: \(Direction.allCases.count)" to the console
print("Total directions: \(Direction.allCases.count)")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trying to use .allCases on an enum that doesn't conform to CaseIterable; the protocol must be explicitly adopted.
  2. Assuming CaseIterable works automatically for enums with associated values; it only works for enums without them (or where Swift can't enumerate all possible associated combinations).
  3. Forgetting .allCases returns the cases in the order they were declared in the source code.
Chapter Summary
  • Conforming an enum to CaseIterable automatically generates an .allCases collection.
  • .allCases lists every case in declaration order.
  • This only works automatically for enums without associated values.
  • .allCases.count is a convenient way to know how many cases an enum has.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.