Lukas Pistrol Logo

Lukas Pistrol

Swift Enum CaseIterable

Let's say we have an enum with different fruits and want to list all of them.

enum Fruits {
  case apple, orange, strawberry
}

One way to achieve this could be to add a static property which holds each case like so:

enum Fruits {
  case apple, orange, strawberry
  
  static var allFruits: [Fruits] {
    [.apple, .orange, .strawberry]
  }
}

Fruits.allFruits.forEach { print($0) }

// Output:
//  apple
//  orange
//  strawberry

Notice how this code does not scale well? For every new fruit we have to add it to the allFruits property as well.

CaseIterable This is where CaseIterable protocol comes in to play. It does exactly what it sounds like: iterating over all of the type's cases. All we have to do is to make Fruits conform to CaseIterable.

enum Fruits: CaseIterable {
  case apple, orange, strawberry
}

Now we can access the allCases property without adding our cases to an array manually.

enum Fruits: CaseIterable {
  case apple, orange, strawberry
}

Fruits.allCases.forEach { print($0) }

// Output:
//  apple
//  orange
//  strawberry

Another article you might like: