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 14,500+ Swift developers and enthusiasts who get my weekly updates.

  • If you are testing against the enum value, then wouldn’t you be doing this:

    func lunch(#day:DayOfTheWeek)->String {

    switch day {

    case .Monday:
    return “Turkey Sandwich”

    }

    rather than using toRaw?

  • Mark Patterson

    Good heads-up, Ms The Robot.

  • Thought about doing it this way? It does tightly couple lunch with the day of the week, for better or worse.

    enum DayOfTheWeek: String{

    case MONDAY = “Monday”
    case TUESDAY = “Tuesday”
    case WEDNESDAY = “Wednesday”
    case THURSDAY = “Thursday”
    case FRIDAY = “Friday”
    case SATURDAY = “Saturday”
    case SUNDAY = “Sunday”

    var lunch: String{
    switch self{
    case .MONDAY:
    return “turkey sandwich”
    case .TUESDAY:
    return “pizza”
    case .WEDNESDAY:
    return “meatball sandwich”
    case .THURSDAY:
    return “ceasar salad”
    case .FRIDAY:
    return “greek salad”
    case .SATURDAY:
    return “turn sandwich”
    case .SUNDAY:
    return “pastrami sandwich”
    }
    }
    }

    println(DayOfTheWeek.fromRaw(“Monday”)?.lunch)
    // “turkey sandwich”

  • Awesome, this makes me excited to finish the Swift.So many possibilities with this language, and it’s so readable!