Getting All Cases Of An Enum

I think my favourite addition to Swift 4.2 might be having the compiler automatically generate an allCases collection for enums.

How Many Cases In My Enum?

It is often useful to know how many cases an enum has or to be able to iterate over all possible cases. Before Swift 4.2 you either needed to use a meta-programming tool like Sourcery or manually maintain the collection:

enum Direction {
  case left
  case right
}

extension Direction {
  static let allItems: [Direction] = [.left, .right]
}

Direction.allItems.count
// 2
Direction.allItems.forEach { print($0) }
// left
// right

Doing it yourself is a pain and fails to work as expected when I add extra cases to the enum and forget about updating my implementation of allItems.

enum Direction {
  case left
  case right
  case up
  case down
}

Direction.allItems.count
// 2 ???

CaseIterable Protocol

Swift 4.2 brings us the CaseIterable protocol. This follows the pattern of Equatable, Comparable and Hashable by having the compiler automatically synthesize the implementation.

All you need to do is declare that your enum conforms to the protocol:

enum Direction: CaseIterable {
  case left
  case right
  case up
  case down
}

The compiler then provides you an allCases that is a collection of all cases of the enum:

Direction.allCases.count
// 4
Direction.allCases.forEach { print($0) }
// left right up down.

Notes:

Further Reading

Never miss a post

iOS Size Classes Cheat Sheet

Subscribe and also get my free iOS Size Classes Cheat Sheet

Success! Now check your email to confirm your subscription and download your free guide to iOS Size Classes.

There was an error submitting your subscription. Please try again.

Unsubscribe at any time. See Privacy Policy
No time to watch WWDC videos?

Sign up to get my iOS posts and news direct to your inbox and also get my free iOS Size Classes Cheat Sheet

OK! Check your inbox (or spam folder) for an email to confirm your details and download your free guide to iOS Size Classes.

There was an error submitting your subscription. Please try again.

Unsubscribe at any time. See Privacy Policy
Archives Categories