NotationMaster
NotationMaster

Reputation: 410

Enumeration behaviour understanding (Intro to App Development with Swift - Lesson 19)

I'm new to coding and am about to finish the "Intro to App Development with Swift" iBook. I am currently in lesson 19, Enumerations and Switch and, at page 8 of the associated playground it shows the following code:

enum LunchChoice {
    case pasta, burger, soup
}

func cookLunch(_ choice: LunchChoice) -> String {
    if choice == .pasta {
        return "🍝"
    } else if choice == .burger {
        return "🍔"
    } else if choice == .soup {
        return "🍲"
    }

    return "Erm... how did we get here?"
}

cookLunch(.soup)

Per se, this is not a problem for me to understand but, once I call cookLunch(.soup), the last return statement doesn't show up. The exercise just below ask me:

try to change the value passed in to cookLunch so that the final else statement is called

And that is where I got stuck because it seems impossible to pass something different to the cookLunch function other than the choices present in the enumeration.

Could you help me understand the sense behind all this and maybe provide me a solution?

Upvotes: 1

Views: 172

Answers (2)

Duncan C
Duncan C

Reputation: 131426

Your instructions say "so that the final else statement is called". That would be the soup return, not the "how did we get here" return. As you say, with 3 lunch choices and 3 if/else statements, one of them will always be invoked. You have to add a 4th lunch choice that doesn't have a corresponding if or else if in order for the "how did we get here" code to execute.

Upvotes: 1

vadian
vadian

Reputation: 285072

You have two options:

  • Comment out the third comparison

    // } else if choice == .soup {
    //      return "🍲"
    
  • Add a fourth case which is not covered by the comparisons

    enum LunchChoice {
        case pasta, burger, soup, steak
    }
    

    and pass it:

    cookLunch(.steak)
    

However nobody would seriously write such an if - else chain, in Swift a switch expression is appropriate

func cookLunch(_ choice: LunchChoice) -> String {
    switch choice {
    case .pasta:  return "🍝"
    case .burger:  return "🍔"
    case .soup: return "🍲"

    default: return "Erm... how did we get here?"
    }
}

Upvotes: 2

Related Questions