Drop me an email if you'd like to hire me (part time) or learn more about what I do. You can read about my experience and references on LinkedIn.
Swift: Failable Enums with Optionals
This is response to Natasha Murashev’s post.
She asked if someone found some better way of handling initializing enums with
optional values. I think here is described a better one.
Natasha published few ways to do that:
This is using check if passed rawValue is nil and appropriate value is
assigned using switch to check all cases (IMO almost perfect), but what if
enum will have 10-15 values? This switch will escalates so quickly!
This is using check if rawValue is nil outside enum which looks poor,
because everywhere enum is created with optional string this check must
This has been described by Natasha as “not as clear / readable” because of
using ?? operator. And this check should be also performed inside some
Here are two checks to be performed before enum is able to be created:
1. Check if rawValue passed to enum initializer is nil
2. Check if enum can be created with passed rawValue
I found that this is a little better option of handling initializing
enums with optional rawValues.
All checks are performed and switch-case check used by Natasha is avoided
so even if enum has 100 values implementation is the same.
Going further it may be simplified using more complex if-statement:
Update: In article at medium.com there is even better solution.