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.
In this page:
Adopting CaseIterable
Adding CaseIterable conformance to an enum automatically synthesizes an .allCases static property listing every case.
Example: Adopting CaseIterable
enum Direction: CaseIterable {
case north, south, east, west
}
for direction in Direction.allCases {
print(direction)
}
Login to try C/C++/Java/PHP code in the editor
Counting Cases
.allCases.count gives the total number of cases without needing to manually count or maintain a separate list.
Example: Counting Cases
enum Direction: CaseIterable {
case north, south, east, west
}
print("Total directions: \(Direction.allCases.count)")
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Trying to use
.allCaseson an enum that doesn't conform toCaseIterable; the protocol must be explicitly adopted. - Assuming
CaseIterableworks automatically for enums with associated values; it only works for enums without them (or where Swift can't enumerate all possible associated combinations). - Forgetting
.allCasesreturns the cases in the order they were declared in the source code.
Chapter Summary
- Conforming an enum to
CaseIterableautomatically generates an.allCasescollection. .allCaseslists every case in declaration order.- This only works automatically for enums without associated values.
.allCases.countis 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: