Iterating Through Enum Cases With CaseIterable In Swift

Treat enum cases as if they were collections with a single move.

Gabriel Theodoropoulos
3 min readMay 20, 2022

--

Photo by Lopsan: https://www.pexels.com/photo/makin-magic-album-sleeve-2191013/

Enums are a vital programming tool in Swift, as they allow to define types that enumerate related values and therefore write code that’s safe and specific. As we all know, enum cases can be either simple, or with associated values that store additional data tied to them. Regardless, it’s often necessary to list all cases or iterate through them for numerous reasons. Even though the obvious way to do that would probably seem to create an array with all available cases manually, there’s a much better approach to achieve that; to let the Swift compiler synthesize that array automatically for us simply by adopting the CaseIterable protocol.

Using CaseIterable

Every time an enum conforms to the CaseIterable protocol, a static property named allCases is made instantly available to us. It is an array containing all enum's cases, so we can operate on them as we would be doing on the elements of any array.

For instance, see the following enum that conforms to CaseIterable, the cases of which represent weekdays:

We can get all cases as an array simply by accessing the allCases property through the Weekdays type like so:

As it’s already said, allCases is an array, so we can use any related API necessary for our cause. We can, for example, just count the number of cases in the enum:

--

--

Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev