Derrick Ho
1 min readFeb 18, 2017

Enums are a great place to hold your constant strings. They allow you to group strings. However, anyone that has used enum string will likely start using them in dictionaries. Maybe you are lucky enough to own that dictionary and can make the KEY of type enum, but more often then not, you will be dealing with KEYs of type string. This means your code may look like this:

d[MyEnum.theValue.rawValue]

The need to always use “rawValue” has been more or less an annoyance that I’ve grown to accept. For the longest time I have grown to accept it because the benefits of using string enums outweigh the cons (i.e. slight verbosity).

That is until I found a way to extend dictionaries…

Inspired by this stack overflow post

There is however one drawback to the approach. You would basically need to overload the subscript method for each enum. That sounds boilerplatey. One possible solution is to have your enum conform to a protocol and use that in your extension

The benefit of this approach is that if you want to use the subscript extension, you need to make the enum conform to UsesRawValue

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response