Swift: Testing optionals for nil

前端 未结 14 678
攒了一身酷
攒了一身酷 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条回答
  •  生来不讨喜
    2020-12-08 09:21

    From swift programming guide

    If Statements and Forced Unwrapping

    You can use an if statement to find out whether an optional contains a value. If an optional does have a value, it evaluates to true; if it has no value at all, it evaluates to false.

    So the best way to do this is

    // swift > 3
    if xyz != nil {}
    

    and if you are using the xyz in if statement.Than you can unwrap xyz in if statement in constant variable .So you do not need to unwrap every place in if statement where xyz is used.

    if let yourConstant = xyz{
          //use youtConstant you do not need to unwrap `xyz`
    }
    

    This convention is suggested by apple and it will be followed by devlopers.

提交回复
热议问题