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 😊

Swift Snippets 🚀

It’s an initiative to share snippets that leverages the…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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