Skip to content
DeveloperMemos

Using CaseIterable in Swift

Swift, Enumerations, CaseIterable1 min read

Enumerations in Swift are a powerful feature that allows you to define a set of related values as a single type. Swift's enum keyword provides a lot of flexibility and allows you to define custom associated values, methods, and more. One of the lesser-known features of Swift's enum is CaseIterable, which allows you to iterate through all the cases of an enum type. In this post, we'll explore how to use CaseIterable in Swift to iterate through enum cases and perform various operations on them.

What is CaseIterable?

CaseIterable is a protocol that was introduced in Swift 4.2. When a type conforms to CaseIterable, Swift automatically generates a static property called allCases, which is an array of all the cases of the enum in the order they were declared. allCases is a collection of the same type as the enum, which means you can use it to perform operations on the enum cases, such as iterating through them, counting them, or generating random cases.

To conform to CaseIterable, you need to add the protocol to the enum declaration:

1enum Direction: CaseIterable {
2 case north, south, east, west
3}

With this code, Swift generates a static property called allCases that contains an array of all the Direction cases:

1let allDirections = Direction.allCases
2// [north, south, east, west]

Using CaseIterable

Now that we know what CaseIterable is, let's look at how to use it. The most common use case for CaseIterable is to iterate through all the cases of an enum, for example, to display them in a list or menu. To do this, you can use a for loop to iterate through the allCases array:

1for direction in Direction.allCases {
2 print(direction)
3}
4// north
5// south
6// east
7// west

You can also use allCases to get the number of cases in the enum:

1let numberOfDirections = Direction.allCases.count
2// 4

Another useful feature of CaseIterable is that you can generate a random case from the enum:

1let randomDirection = Direction.allCases.randomElement()
2print(randomDirection)
3// east

Finally, you can use allCases to perform other operations on the enum cases. For example, you can use it to create a custom initializer that takes a string as input and returns an optional enum case:

1enum Gender: String, CaseIterable {
2 case male, female
3
4 init?(rawValue: String) {
5 self = Gender.allCases.first { "\($0)" == rawValue.lowercased() } ?? .male
6 }
7}
8
9let gender = Gender(rawValue: "MALE")
10print(gender)
11// Optional(Gender.male)

Conclusion

In this post, we learned about CaseIterable, a protocol that allows you to iterate through all the cases of an enum in Swift. We saw how to use allCases to perform various operations on the enum cases, such as iterating through them, counting them, or generating random cases.