【问题标题】:if-case pattern matching - Variable binding in a condition requires an initializerif-case 模式匹配 - 条件中的变量绑定需要初始化器
【发布时间】:2017-04-04 14:07:05
【问题描述】:

我正在阅读 Big Nerd Ranch 的 Swift Programming 一书(第 2 版),在关于 Switch 语句的章节中,有一小部分是关于 in-cases 以及如何使用它们的。在描述如何实现具有多个条件的 if-case 时,这是本书显示的代码:

...
let age = 25

if case 18...35 = age, age >= 21 {
    print("In cool demographic and of drinking age")
} 

但是,当我尝试在我的 Xcode 游乐场中实现这个(完全按照它的样子)时,我收到一个错误(“条件中的变量绑定需要一个初始化程序”)

似乎年龄> = 21位是实际问题,因为这个

let age = 25

if case 18...35 = age{
    // Same thing
}

工作正常。我在多条件代码中做错了什么?

【问题讨论】:

  • 你在使用 Swift 2 吗? (如果是,为什么?)在 Swift 3.1 中编译对我来说很好
  • 正如@Hamish 提到的,它在这里也很合规......你使用的是什么版本的 Swift?
  • Swift 2.2 确实给出了该错误消息。 Swift 2 的语法是 if case 18...35 = age where age >= 21 {
  • 引用标题为必要的硬件和软件的部分:本书是为 Swift 3.0 和 Xcode 8.0 编写的。许多示例不适用于旧版本的 Xcode。
  • 但你真的应该升级到 Swift 3 - 最新版本的 Xcode 甚至不支持 Swift 2。

标签: swift pattern-matching if-case


【解决方案1】:

我正在阅读 Big Nerd Ranch 的 Swift Programming 一书(第 2 版)...

正如the official book web page 所述,本书包括带有Xcode 8 的Swift 版本3.0

您可能正在使用 Xcode 7.x 或更早版本,在 Swift 2 中,它应该是:

if case 18...35 = age where age >= 21 {
    print("In cool demographic and of drinking age")
}

斯威夫特 3:

if case 18...35 = age, age >= 21 {
    print("In cool demographic and of drinking age")
}

备注:如果第一个代码 sn-p 已经在 Xcode 8 操场上编译,它会报以下编译时错误:

错误:预期的 ',' 连接多子句条件的部分

建议将where 更改为,

在使用可选绑定时应用相同的语法 - 例如 -

斯威夫特 2:

if let unwrappedString = optionalString where unwrappedString == "My String" {
    print(unwrappedString)
}

斯威夫特 3:

if let unwrappedString = optionalString, unwrappedString == "My String" {
    print(unwrappedString)
}

有关将where 更改为, 的更多信息,您可能需要查看Restructuring Condition Clauses Proposal

所以,请务必将使用的 IDE 更新到最新版本(可编译 Swift 3)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    相关资源
    最近更新 更多