Equivalence of short-cut optional binding syntax in Swift

与世无争的帅哥 提交于 2020-01-03 00:38:48

问题


Given

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?


回答1:


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")
}

which results in

nil
"Nope"

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.



来源:https://stackoverflow.com/questions/26170375/equivalence-of-short-cut-optional-binding-syntax-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!