Swift snippet #11 β€” RawRepresentable

Ritesh Gupta
Mar 20, 2017 Β· 2 min read

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 😊

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer β€” welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store