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

前端 未结 3 1487
醉梦人生
醉梦人生 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:26

    if let is used to get rid of the optional. If you want to see when the variable is nil use

    if let y: Int = x {
    // This occurs if you are able to give a non-nil value to the variable
    } else {
    // This occurs if the optional x is nil
    }
    

    as far as I know you shouldn't try declare the type of a constant in the if let statement to be optional because that kind of defeats the purpose of the if let statement.

提交回复
热议问题