---
title: "#320: Counting Enum Cases with CaseIterable 🐤"
url: https://littlebitesofcocoa.com/320-counting-enum-cases-with-caseiterable
author: Jake Marsh
date: 2018-11-30
published: 2018-11-30
topics: ["Swift"]
description: "Back in Bite #292 we looked at Sourcery and how we could use it to add handy properties like count to our Swift enums."
---

# #320: Counting Enum Cases with CaseIterable 🐤

By Jake Marsh, November 30, 2018. HTML: https://littlebitesofcocoa.com/320-counting-enum-cases-with-caseiterable

Back in [Bite #292](https://littlebitesofcocoa.com/292-metaprogramming-with-sourcery) we looked at [Sourcery](https://github.com/krzysztofzablocki/Sourcery) and how we could use it to add handy properties like `count` to our Swift enums. [Sourcery](https://github.com/krzysztofzablocki/Sourcery) is still just as awesome but [Swift 4.2](https://swift.org/blog/swift-4-2-released/) 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_:

``` swift
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 <i>number</i> of spaceships in our app. We could extend our _enum_, adding a `count` property:

``` swift
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 <i>also</i> update this extension property's implementation as well. Yuck.

In [Swift 4.2](https://swift.org/blog/swift-4-2-released/) we can solve this quite elegantly, by ditching our extension and instead conforming our _enum_ to the new `CaseIterable` protocol:

``` swift
enum Spaceships : CaseIterable {
  case tantiveIV
  case ghost
  case falcon
}
```

Now, we can access the number of spaceships anywhere in our code:

``` swift
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](mailto:hello@littlebitesofcocoa.com).

<p></p>
