Norway


Topics

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 Spaceships {
  case tantiveIV
  case ghost
  case falcon
}

We’ll be adding to the list of in our enum frequently as new spaceships are added, and we’d like to display the number of spaceships in our . 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 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.



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here