Topics

#320: Counting Enum Cases with CaseIterable 🐤

Topics

Back in Bite #292 we looked at Sourcery and how we could use it to add handy properties like count to our Swift enums. Sourcery is still just as awesome but Swift 4.2 actually removed the need for using it in this... case. 🤭 Let's take a look.

We'll start with the problem we're trying to solve. Let's imagine a simple enum:

enum Spaceships {
  case tantiveIV
  case ghost
  case falcon
}

We'll be adding to the list of cases in our enum frequently as new spaceships are added, and we'd like to display the number of spaceships in our app. We could extend our enum, adding a count property:

extension Spaceships {
  static var count: Int {
    return ([
      .tantiveIV,
      .ghost,
      .falcon
    ] as [Spaceships]).count
  }
}

Maintaining this code will not be fun. As we add new enum cases, we'll need to never forget to always also update this extension property's implementation as well. Yuck.

In Swift 4.2 we can solve this quite elegantly, by ditching our extension and instead conforming our enum to the new CaseIterable protocol:

enum Spaceships : CaseIterable {
  case tantiveIV
  case ghost
  case falcon
}

Now, we can access the number of spaceships anywhere in our code:

print(Spaceships.allCases.count)

Neat!

We're using count for simplicity here, but as the name suggests, the allCases static property that CaseIterable adds to our enums of course allows us to easily iterate through our enum's cases.

That's all for today, have a question or idea for a Bite? Send it to hello@littlebitesofcocoa.com.