Swift snippet #11 โ€” RawRepresentable

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 ๐Ÿ˜Š

Itโ€™s an initiative to share snippets that leverages the great power of Swift ๐Ÿค˜

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
Ritesh Gupta

Ritesh Gupta

iOS Developer

More from Medium

Threads & Concurrency In Swift

Multiple Threading swift

Clean architectures: Inner and Outer-Scene layers

You can get that easily by using single variable and make it public.

iOS library support both Cocoapods and Swift Package Manager