枚举行为理解(Swift 应用程序开发简介 - 第 19 课)

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

我是编码新手,即将完成 "Intro to App Development with Swift" iBook。我目前正在学习第 19 课,枚举和开关,在相关操场的第 8 页,它显示了以下代码:

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)

本身,这不是我理解的问题,但是,一旦我调用 cookLunch(.soup),最后的 return 语句就不会出现。 下面的练习问我:

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

这就是我被卡住的地方,因为除了枚举中存在的选择之外,似乎不可能将不同的东西传递给 cookLunch 函数。

你能帮我理解这一切背后的意义,也许能给我一个解决方案吗?

您有两个选择:

  • 注释掉第三个比较

    // } else if choice == .soup {
    //      return ""
    
  • 添加比较未涵盖的第四个案例

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

    并通过它:

    cookLunch(.steak)
    

然而没有人会认真地写这样一个 if - else 链,在 Swift 中 switch 表达式是合适的

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

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

您的说明是 "so that the final else statement is called"。那将是汤 return,而不是 "how did we get here" return。正如您所说,有 3 个午餐选择和 3 个 if/else 语句,其中一个将始终被调用。您必须添加没有相应 if 或 else if 的第 4 次午餐选择才能执行 "how did we get here" 代码。