Swift: Testing optionals for nil

前端 未结 14 688
攒了一身酷
攒了一身酷 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:17

    Swift 3.0, 4.0

    There are mainly two ways of checking optional for nil. Here are examples with comparison between them

    1. if let

    if let is the most basic way to check optional for nil. Other conditions can be appended to this nil check, separated by comma. The variable must not be nil to move for the next condition. If only nil check is required, remove extra conditions in the following code.

    Other than that, if x is not nil, the if closure will be executed and x_val will be available inside. Otherwise the else closure is triggered.

    if let x_val = x, x_val > 5 {
        //x_val available on this scope
    } else {
    
    }
    

    2. guard let

    guard let can do similar things. It's main purpose is to make it logically more reasonable. It's like saying Make sure the variable is not nil, otherwise stop the function. guard let can also do extra condition checking as if let.

    The differences are that the unwrapped value will be available on same scope as guard let, as shown in the comment below. This also leads to the point that in else closure, the program has to exit the current scope, by return, break, etc.

    guard let x_val = x, x_val > 5 else {
        return
    }
    //x_val available on this scope
    

提交回复
热议问题