Enums and CaseIterable in Swift

In your journeys with Swift since 4.2 released, you may have seen the CaseIterable protocol when working with enums. Since this is a relatively new language feature in 4.2, you might wonder what that is or what it does. In this article on raywenderlich.com, Getting to Know Enum, Struct and Class Types in Swift, Adam Rush gives a very nice, concise description of what the purpose of CaseIterable is and how it works.

CaseIterable Enums in Swift are great for holding a list of items such as our example list of colors. To make enums even more powerful, Swift 4.2 added a new protocol named CaseIterable that provides a collection of all the values of the conformer.

At compile time, Swift will automatically create an allCases property that is an array of all your enum cases, in the order you defined them.

Using CaseIterable is very simple. All you have to do is declare the conformance in the definition of ColorName as shown below:

enum ColorName: String, CaseIterable {
  case black, silver, gray, white, maroon, red, purple, fuchsia, green, lime, olive, yellow, navy, blue, teal, aqua 

You can then use the allCases property whose type is [ColorName]. Add the following to the end of your playground:

for color in ColorName.allCases {
  print("I love the color \(color).")

In the console, you’ll see 16 lines printed — one for every color in ColorName.