问题描述
给定
var maybeInt: Int?
以下两个条件语句有何不同?
how to the following two conditional statements differ?
// (1)
if let y = maybeInt {
y
} else {
println("Nope")
}
// (2)
if let y = maybeInt? {
y
} else {
println("Nope")
}
他们的行为似乎完全一样.前者是后者的捷径?
They seem to behave exactly the same. Is the former a short-cut for the latter?
推荐答案
第二种语法是可选的 chaining —— 只是在链接运算符之后没有任何内容.它访问它之前的任何可选项(如果可选项不是 nil
),允许链接属性访问或对可选项内容的方法调用,并将结果包装在一个可选项中.将它放在 if let
中可以解开那个可选的.
The second syntax is optional chaining — just with nothing after the chaining operator. It accesses whatever optional comes before it (if the optional is not nil
), allows chaining property accesses or method calls on the optional's contents, and wraps the result in an optional. Putting it in an if let
unwraps that optional.
换句话说,第二个语法中额外的 ?
在这里实际上是一个空操作.
In other words, the additional ?
in the second syntax is effectively a no-op here.
然而,虽然它在你的例子中没有效果,?
本身仍然在做可选链,正如你所看到的
However, though it has no effect in your example, ?
on its own is still doing optional chaining, as you can see with
if let y: Int? = maybeInt {
y
} else {
println("Nope")
}
if let y: Int? = maybeInt? {
y
} else {
println("Nope")
}
结果
nil
"Nope"
因为虽然 maybeInt?==maybeInt
——一个无操作",在上面的意义上——(以及将 nil
赋值给一个 Int?
有效)第二个表达式遇到 nil
在 maybeInt
的可选链接上失败.
because while maybeInt? == maybeInt
— a "no op", in the sense above — (and an assignment of nil
to an Int?
works) the second expression encounters nil
on the optional chaining of maybeInt
and fails.
这篇关于Swift 中快捷可选绑定语法的等效性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!