使用“如果让..."有很多表达 [英] Using "if let..." with many expressions
问题描述
Swift 的这个习语很有道理
This idiom of Swift makes good sense
if let x = someDict[someKey] { ... }
然而,我真正想要的是
if let x = someDict[someKey], y = someDict[someOtherKey] { ... }
正如所写的那样,这并没有错,但是这个想法可能吗?
As written this is not incorrect, but is this idea possible?
推荐答案
Swift 1.2 更新
从 Swift 1.2 开始,if let
允许解包多个选项,因此您现在可以编写此代码,如您的示例所示:
Since Swift 1.2, if let
allows unwrapping multiple optionals, so you can now just write this, as in your example:
if let x = someDict[someKey], y = someDict[someOtherKey] { … }
您甚至可以交错条件,例如:
You can even interleave conditions such as:
if let x = someDict[someKey] where x == "value", y = someDict[someOtherKey] { … }
这在 Swift 1.2 之前是有效的
如果没有丑陋的强制包装,您将如何做到这一点:
Here's how you would do it without an ugly force-upwrapping:
switch (dict["a"], dict["b"]) {
case let (.Some(a), .Some(b)):
println("match")
default:
println("no match")
}
实际上还是很冗长.
之所以有效,是因为表单 Type?
的可选类型实际上是 Optional
的简写,它是一个大致如下所示的枚举:
This works because an optional type of the form Type?
is actually shorthand for Optional<Type>
, which is an enum that looks roughly like this:
enum Optional<T> {
case None
case Some(T)
}
然后您可以像任何其他枚举一样使用模式匹配.
You can then use pattern matching as for any other enum.
我见过有人写过这样的辅助函数(抱歉没有注明出处,我不记得在哪里看到的):
I've seen people write helper functions like this one (sorry for the lack of attribution, I don't remember where I saw it):
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
构造,即像这样:
Then you can keep using the if let
construct, namely like this:
if let (a, b) = unwrap(dict["a"], dict["b"]) {
println("match: \(a), \(b)")
} else {
println("no match")
}
这篇关于使用“如果让..."有很多表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!