Member-only story
Iterating Through Enum Cases With CaseIterable In Swift
Treat enum cases as if they were collections with a single move.
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: