为什么多个解包选项是不可能的?

Why are multiple unwrapping optionals impossible?

我一直在玩 swift 中的选项。我经常使用条件展开模式:

var myOptional: AnyObject?
if let unwrapped = myOptional {
// do stuff
}

然而,有时我有两个可选值,我只想在它们都非零时使用。因此,我尝试使用以下语法:

var myOptional: AnyObject?
var myOtherOptional: AnyObject?
if let unwrapped = myOptional && let otherUnwrapped = myOtherOptional? {
// do stuff
}

我试过将这两部分放在括号中等,但似乎没有办法做到这一点。我不能这样做有充分的理由吗?显然我可以将一个语句嵌入另一个语句,但我更愿意将它们全部放在一行中。

Swift 1.2 开始,您可以展开多个选项和条件。

The “if let” construct has been expanded to allow testing multiple optionals and guarding conditions in a single if (or while) statement using syntax similar to generic constraints: if let a = foo(), b = bar() where a < b, let c = baz() { } This allows you to test multiple optionals and include intervening boolean conditions, without introducing undesirable nesting (i.e., to avoid the “pyramid of doom”).

因为语言不支持。

the document中:

The value of any condition in an if statement must have a type that conforms to the BooleanType protocol. The condition can also be an optional binding declaration, as discussed in Optional Binding.

condition 必须是 "expression of BooleanType" 或 "optional binding declaration"。 "optional binding declaration" 不是 "expression",所以你不能加入 &&

相反,您可以使用 switch:

switch (myOptional, myOtherOptional) {
case let (.Some(unwrapped), .Some(otherUnwrapped)):
    // do stuff
    println("\(unwrapped), \(otherUnwrapped)")
default:
    break
}
    var myOptional: AnyObject?
    var myOtherOptional: AnyObject?
    let unwrapped: AnyObject? = myOptional,  otherUnwrapped: AnyObject? = myOtherOptional?
    if (unwrapped != nil && otherUnwrapped != nil) {
       // Do Stuff 
    }

这是您可以使用的另一种方法。 Swift 一天比一天好

唯一的办法就是嵌套if语句。我认为这是因为苹果将其实现为 syntactic sugar。所以预编译器转换

var myOptional: AnyObject?
if let unwrapped = myOptional {
    // do stuff
}

进入

var myOptional: AnyObject?
if myOptional != nil {
    let unwrapped = myOptional
    // do stuff
}

您当然可以在一个 if 中自己完成此操作,但这只会使您的代码更漂亮一点。不利的一面是,您在调试时不知道是哪一个导致了崩溃。

有关详细信息,请参阅 documentation