Why does Swift's optional binding succeed with 'nil' in certain cases?

后端 未结 2 471
梦毁少年i
梦毁少年i 2020-12-20 02:08

Apple\'s Swift language documentation says that optional binding (a.k.a. if let) will \"check for a value inside an optional\" and \"extra

相关标签:
2条回答
  • 2020-12-20 02:37

    I interpret this differently:

    var x: Int? = 1
    
    if let y1: Int = x {
        println("y1 = \(y1)") 
    }
    
    //prints y = 1, the optional was checked, contains a value and passes it
    
    var x: Int? = nil
    
    if let y1: Int = x {
        println("y1 = \(y1)") 
    }
    
    //does not execute because x does not contain value that can be passed to a non optional y
    
    var x: Int? = nil
    
    if let y1: Int? = x {
        println("y1 = \(y1)")
    }
    // y = nil, since y is optional and can hold a value of x which is nil, then it passes nil
    

    Optional binding is for checking if an optional contains a value to pass to a non optional parameter.

    0 讨论(0)
  • 2020-12-20 02:39

    You assigned an optional Int to an optional Int. The assignment did succeed. It will always succeed, whether the optional Int contained an Int or not.

    0 讨论(0)
提交回复
热议问题