0
0
Swiftprogramming~5 mins

Iterating enum cases with CaseIterable in Swift

Choose your learning style9 modes available
Introduction

Sometimes you want to look at all options in a list. Enums can hold these options. CaseIterable helps you easily go through each option one by one.

You want to show all choices in a menu.
You need to check every possible state in a game.
You want to print all colors available in your app.
You want to count how many options an enum has.
Syntax
Swift
enum YourEnumName: CaseIterable {
    case firstCase
    case secondCase
    case thirdCase
}

for item in YourEnumName.allCases {
    print(item)
}

Adding CaseIterable to your enum lets you use allCases to get all cases as a collection.

You can loop over allCases with a for loop to access each case.

Examples
This example lists all four directions by looping through the enum cases.
Swift
enum Direction: CaseIterable {
    case north, south, east, west
}

for direction in Direction.allCases {
    print(direction)
}
This example counts how many fruits are in the enum using allCases.
Swift
enum Fruit: CaseIterable {
    case apple
    case banana
    case cherry
}

let fruits = Fruit.allCases
print("We have \(fruits.count) fruits.")
Sample Program

This program prints all the days in the workweek by looping through the enum cases.

Swift
enum Weekday: CaseIterable {
    case monday, tuesday, wednesday, thursday, friday
}

print("Days of the workweek:")
for day in Weekday.allCases {
    print(day)
}
OutputSuccess
Important Notes

Only enums without associated values can use CaseIterable automatically.

You can add CaseIterable to enums with raw values too.

The order of allCases matches the order you write the cases.

Summary

CaseIterable lets you get all enum cases easily.

You use allCases to loop through every case.

This helps when you want to show or count all options in an enum.