Swift Enums: Don’t Forget to Unwrap!

I was working with an enum this morning, when I got this misleading error:

Swift Enum Error

It took me a while to figure out that the reason the error kept popping up is not because the enum case MONDAY does not exist (which it clearly does!), but because there is a chance that when I convert my lunch day fromRaw to a DayOfTheWeek enum type, it might not exist.

In other words, a converted enum value is an optional – hence the ‘DayOfTheWeek?’ with the question mark in the error message. For it to work, I need to unwrap my optional like this:

In retrospect, this seems obvious, but getting into the habit of unwrapping optionals all the time is definitely a challenge in Swift. Hopefully this post helps someone out, and I’ll make sure to file a Radar with Apple for better error messagingĀ in this scenario.

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.