可以以某种方式在Swift中为一行中的多个变量使用可选绑定吗?我需要做这样的事情:我可以以某种方式在Swift中对一个行中的多个变量使用可选绑定吗?
if let foo = fooOptional && let bar = barOptional {
// ...
}
可以以某种方式在Swift中为一行中的多个变量使用可选绑定吗?我需要做这样的事情:我可以以某种方式在Swift中对一个行中的多个变量使用可选绑定吗?
if let foo = fooOptional && let bar = barOptional {
// ...
}
更新雨燕1.2:
从雨燕1.2(的Xcode 6.3测试版),您可以解开多个自选与if let
:
if let foo = fooOptional, bar = barOptional {
println("\(foo), \(bar)")
}
雨燕1.2之前
你不能用if
,但你可以用switch
使用"Value-Binding Pattern":
switch (fooOptional, barOptional) {
case let (.Some(foo), .Some(bar)):
println("\(foo), \(bar)")
default:
break
}
这是一个非常合理的增强请求,但根据情况你不能这样做。有各种各样的原因,但我喜欢想的方式只是这样:if let
是真的一个字。这是两个字,但搭配if let
意味着一些特殊的东西,就好像它本身就是一个关键字。本身,if
具有不同的含义;本身,let
有不同的含义。因此,你不能像这样在后面放置一个单独的let
。
其结果是,我经常结束嵌套if let
子句的级联。我相信你的问题的原因是你也这样做,你想避免它。但你不能。另一种方法是完全跳过if let
,强制打开您的选择项,并希望当其中一个为零时不会崩溃。
感谢您的回答。顺便说一句我看到了下面的代码 - https://gist.github.com/jhaberstro/878f7f2043f922f0d06c,但评论说“段错误 - 似乎是代码中的编译器错误” – FrozenHeart 2014-11-24 17:02:51
这是一个有点笨拙,但是你可以用switch
您变量的元组这样做:
var fooOptional: String? = "foo"
var barOptional: String? = "bar"
switch (fooOptional, barOptional) {
case let (.Some(foo), .Some(bar)):
println(foo + bar)
default:
break
}
我用这个被向下钻取到嵌套字典的时间,就像一个大的JSON对象 - 这是伟大的,因为你可以分别处理每个错误情况:
switch (dict["foo"], dict["foo"]?["bar"], dict["foo"]?["bar"]?["baz"]) {
case let (.Some(foo), .Some(bar), .Some(baz)):
// do things
case (.None, _, _):
// no foo
case (_, .None, _):
// no bar
default:
// no baz
}
Swift之前1.2
我喜欢使用switch
声明,尤其是如果你想处理四种不同的情况。
但是,如果你在这两个自选是Some
的情况下仅仅是兴趣,你也可以这样做:
if let (firstName, lastName) = unwrap(optionalFirstName, optionalLastName) {
println("Hello \(firstName) \(lastName)!")
}
如果是这种unwrap
函数的定义:
func unwrap<T1, T2>(optional1: T1?, optional2: T2?) -> (T1, T2)? {
switch (optional1, optional2) {
case let (.Some(value1), .Some(value2)):
return (value1, value2)
default:
return nil
}
}
更多过载:https://gist.github.com/tomlokhorst/f9a826bf24d16cb5f6a3
我喜欢这个选项,当你只是想实现“如果所有可用”的情况下,在代码中的默认开关感觉像是矫枉过正,这将保持你的代码清洁。 – 2014-12-08 19:22:51
你的答案比我的好!:) – matt 2014-11-24 17:00:32
你可以用刚刚发布的Swift 1.2! http://www.codingexplorer.com/multiple-optional-bindings-swift-1-2/(我知道这个问题很旧,但为了防止任何人看到,你可能想更新你的答案) – SeeMeCode 2015-02-15 01:15:06