我正在研究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
}
工作正常。我在多条件代码中做错了什么?
答案 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)。