Swift 4.2: Enumerable Enum

What is CaseIterable?

It’s a protocol, introduced in Swift 4.2. It automatically synthesises a collection of all the cases in your enum in the order that is defined, however you have to provide your own allCases implementation if your enum contains associated values (more on that later).

Example

Lets look at a delicious example 🍕🤤

enum Pizza: CaseIterable {
case neapolitan
case chicago
case newYork
case sicilian
case greek
case california
}
let pizzaTypes = Pizza.allCases.map {
"\($0)"
}
print(pizzaTypes) // ["neapolitan", "chicago", "newYork", "sicilian", "greek", "california"]

Limitations

The first limitation is automatic synthesis. Because the compiler automatically synthesise conformance to the CaseIterable protocol, one can only declare the conformance in the same file where the type is defined i.e on the type definition itself or in the same file as an extension. Lets look at some illustrations.

// Pizza.swift
enum Pizza: CaseIterable {
....
}
**** OR ****
enum Pizza {
....
}
extension Pizza: CaseIterable { }
// Pizza.swift
enum Pizza {
....
}

// SomeOtherFile.swift
extension Pizza: CaseIterable { }
enum Pizza {
case neapolitan(NeapolitanTypes)
case chicago
}
enum NeapolitanTypes {
case marinara
case margherita
}
extension Pizza: CaseIterable {
static var allCases: [Pizza] {
return [.neapolitan(.marinara),
.neapolitan(.margherita),
.chicago]
}
}

Conclusion

In my opinion CaseIterable is a useful protocol to adopt, it provides a useful functionality that you can bolt on to your enums. However there are some limitations to consider before embracing it, as we saw earlier these limitation can easily be overcome but with a small price of maintenance.

--

--

A Software Engineer with a passion for technology. Working as an iOS Developer @BBC

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Melvin John

Melvin John

A Software Engineer with a passion for technology. Working as an iOS Developer @BBC