Swift中快捷方式可选绑定语法的等效项 [英] Equivalence of short-cut optional binding syntax in Swift

查看:62
本文介绍了Swift中快捷方式可选绑定语法的等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给予

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?起作用),第二个表达式在maybeInt的可选链上遇到nil并失败了.

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中快捷方式可选绑定语法的等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆