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 π οΈ:
- only applicable for enums having
RawValue
asInt
- 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 π