gpt4 book ai didi

swift - if-case 模式匹配 - 条件中的变量绑定(bind)需要初始化器

转载 作者:行者123 更新时间:2023-11-28 06:21:48 26 4
gpt4 key购买 nike

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

...
let age = 25

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

然而,当我尝试在我的 Xcode playground 中实现这个(完全按照原样)时,我收到一个错误(“条件中的变量绑定(bind)需要一个初始化程序”)

看来 age >= 21 位才是真正的问题,因为这个

let age = 25

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

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

最佳答案

I'm working through Big Nerd Ranch's Swift Programming book (2nd edition) ...

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")
}

swift 3:

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

备注:如果第一个代码片段已经在 Xcode 8 playground 编译,它会提示以下编译时错误:

error: expected ',' joining parts of a multi-clause condition

建议将 where 更改为 ,

工作时应用相同的语法 - 例如 - 使用可选绑定(bind):

swift 2:

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

swift 3:

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

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

因此,确保将使用的 IDE 更新到最新版本(编译 Swift 3)。

关于swift - if-case 模式匹配 - 条件中的变量绑定(bind)需要初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43209607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com