Swift: Testing optionals for nil

前端 未结 14 679
攒了一身酷
攒了一身酷 2020-12-08 08:51

I\'m using Xcode 6 Beta 4. I have this weird situation where I cannot figure out how to appropriately test for optionals.

If I have an optional xyz, is the correct w

14条回答
  •  猫巷女王i
    2020-12-08 09:28

    To add to the other answers, instead of assigning to a differently named variable inside of an if condition:

    var a: Int? = 5
    
    if let b = a {
       // do something
    }
    

    you can reuse the same variable name like this:

    var a: Int? = 5
    
    if let a = a {
        // do something
    }
    

    This might help you avoid running out of creative variable names...

    This takes advantage of variable shadowing that is supported in Swift.

提交回复
热议问题