Optional binding of nil literal vs. variable that is nil in Swift

前端 未结 3 1485
醉梦人生
醉梦人生 2021-01-07 13:50

In Swift, why does

var x: Int? = nil
if let y: Int? = x { ... }

behave differently from

if let y: Int? = nil { ... }
         


        
3条回答
  •  [愿得一人]
    2021-01-07 14:41

    if let y: Int? = nil { ... }
    

    is equivalent to

    if let y: Int? = nil as Int?? { ... }
    

    is equivalent to

    if let y: Optional = Optional>() { ... }
    

    This tries to cast Optional> to Optional, and it fails because Optional>() does not contains Optional value.


    Oneliner equivalent to

    var x: Int? = nil
    if let y: Int? = x { ... } 
    

    is

    if let y: Int? = nil as Int? { ... } 
    

    ADDED:

    As I answered on What does Swift's optional binding do to the type it's arguments?.

    if let y: Int? = nil as Int? { ... }
    

    is compiled as:

    if let y:Int? = nil as Int? as Int?? { ... }
    

    Here, we should mind that nil as Int? as Int?? is not equivalent to nil as Int??. The former is Optional(Optional()), but the latter is Optional>().

    With this in mind, I think,

    So the optional binding in my first example (does indeed) "check inside" and finds nil, which is perfectly valid to assign to Int?; but my second checks and finds Optional(nil), which can't be assigned to Int?

    The first example "check inside" of Int?? and just finds Optional() value that is Int? type which can be assigned to Int?; But the second one finds nothing to be assigned and fails.

提交回复
热议问题