← 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.

Adopting CaseIterable

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

Example: Adopting CaseIterable

markup
enum Direction: CaseIterable {
    case north, south, east, west
}
for direction in Direction.allCases {
    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
enum Direction: CaseIterable {
    case north, south, east, west
}
print("Total directions: \(Direction.allCases.count)")
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.