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:
Syntax
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
// 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)
}
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
// 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)")
Login to try C/C++/Java/PHP code in the editor
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
- 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: