gpt4 book ai didi

swift - 将 "if let..."与许多表达式一起使用

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

Swift 的这个习语很有道理

if let x = someDict[someKey] { ... }

然而,我真正想要的是

if let x = someDict[someKey], y = someDict[someOtherKey] { ... }

正如所写,这并没有错,但是这个想法可能吗?

最佳答案

Swift 1.2 更新

自 Swift 1.2 起,if let允许解包多个可选项,所以你现在可以像你的例子一样写这个:

if let x = someDict[someKey], y = someDict[someOtherKey] { … }

您甚至可以交错条件,例如:

if let x = someDict[someKey] where x == "value", y = someDict[someOtherKey] { … }

这在 Swift 1.2 之前有效

如果没有丑陋的强制包装,您将如何做到这一点:

switch (dict["a"], dict["b"]) {
case let (.Some(a), .Some(b)):
println("match")
default:
println("no match")
}

实际上还是很冗长。

之所以有效,是因为 Type? 形式的可选类型实际上是 Optional<Type> 的简写,这是一个大致如下所示的枚举:

enum Optional<T> {
case None
case Some(T)
}

然后您可以像对任何其他枚举一样使用模式匹配。

编辑:我见过有人写这样的辅助函数(抱歉,我不记得是在哪里看到的):

func unwrap<A, B>(a: A?, b: B?) -> (A, B)? {
switch (a, b) {
case let (.Some(a), .Some(b)):
return (a, b)
default:
return nil
}
}

然后你可以继续使用if let构建,即像这样:

if let (a, b) = unwrap(dict["a"], dict["b"]) {
println("match: \(a), \(b)")
} else {
println("no match")
}

关于swift - 将 "if let..."与许多表达式一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24118900/

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