gpt4 book ai didi

swift - 在 Swift 中没有 switch 语句的 "case"是什么意思?

转载 作者:IT王子 更新时间:2023-10-29 05:35:07 24 4
gpt4 key购买 nike

我遇到了这段代码,它是 Swift Algorithm Club 中链表的 Swift 实现的一部分。 .在整个实现过程中,作者在解包可选之前紧跟在 while 语句之后使用 case let。我从未见过在 switch 语句的上下文之外使用 case 关键字,我想知道它到底做了什么?它会以某种方式强制转换 let next 吗? = node.next 部分为 true 或 false,可能取决于 next? 是否变为 nil?

public var last: Node? {
if var node = head {
while case let next? = node.next {
node = next
}
return node
} else {
return nil
}
}

最佳答案

这是 Optional Pattern .它测试并解包一个 Optional,仅当 Optional 为非 nil 时才执行条件。

关键字 case 是必需的,因为它遵循原始的 switch...case 语法。 case 测试一个模式,如果匹配则执行下面的语句。在您的示例中, let next? 是模式。如果该值被解包并分配,则 case 匹配并执行您的代码。

来自文档:

Optional Pattern

An optional pattern matches values wrapped in a Some(Wrapped) case of an Optional or ImplicitlyUnwrappedOptional enumeration. Optional patterns consist of an identifier pattern followed immediately by a question mark and appear in the same places as enumeration case patterns.

Because optional patterns are syntactic sugar for Optional and ImplicitlyUnwrappedOptional enumeration case patterns, the following are equivalent:

let someOptional: Int? = 42
// Match using an enumeration case pattern
if case .Some(let x) = someOptional {
print(x)
}

// Match using an optional pattern
if case let x? = someOptional {
print(x)
}

The optional pattern provides a convenient way to iterate over an array of optional values in a for-in statement, executing the body of the loop only for non-nil elements.

let arrayOfOptionalInts: [Int?] = [nil, 2, 3, nil, 5]
// Match only non-nil values
for case let number? in arrayOfOptionalInts {
print("Found a \(number)")
}
// Found a 2
// Found a 3
// Found a 5

关于swift - 在 Swift 中没有 switch 语句的 "case"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37738614/

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