if-case模式匹配 - 条件中的变量绑定需要初始化程序

时间:2017-04-04 14:07:05

标签: swift pattern-matching if-case

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

...
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
}

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

1 个答案:

答案 0 :(得分:1)

  

我正在通过Big Nerd Ranch的Swift编程书(第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")
}

备注:如果在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)。