Swift snippet #11 β€” RawRepresentable

Ritesh Gupta
Swift Snippets πŸš€
2 min readMar 20, 2017

Monday, 20th March, 2017

You can find its Gist here!

The above snippet creates items & itemsCount properties on every enum which has RawValue as Int.

enum City: Int {

case delhi
case bangalore
case mumbai
}

With the help of above snippet, to get the entire the list of cases we can do City.items or City.itemsCount to get the count πŸš€

Since the advent of Swift, we all have been using Enums a lot lately in our apps! And why not, they are super cool and so powerful. But they have this big limitation where we explicitly need to provide a computed var to list all the items or even items count, something like:

extension City {

static var items: [City] {
return [.delhi, .bangalore, .mumbai]
}
static var itemsCount: int {
return items.count
}
}

Nothing is wrong with the above code but its not awesome πŸ˜“ Everytime we add a new case, we have to update our items, failing of which could lead to bugs πŸ› No one likes them so how about we automate it to make it work out of the box & thus the above snippet πŸ˜„

Big thanks to Nate Cook for making it even more awesome!!!

It has two limitations though πŸ› οΈ:

  1. only applicable for enums having RawValue as Int
  2. not applicable for discontinuous cases nor the ones starting from a value other than 0

If you are wondering about the inception of Swift-Snippets or want to checkout more such snippets, you can find them here 😊

--

--