Swift: Testing optionals for nil

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

    One of the most direct ways to use optionals is the following:

    Assuming xyz is of optional type, like Int? for example.

    if let possXYZ = xyz {
        // do something with possXYZ (the unwrapped value of xyz)
    } else {
        // do something now that we know xyz is .None
    }
    

    This way you can both test if xyz contains a value and if so, immediately work with that value.

    With regards to your compiler error, the type UInt8 is not optional (note no '?') and therefore cannot be converted to nil. Make sure the variable you're working with is an optional before you treat it like one.

    0 讨论(0)
  • 2020-12-08 09:36

    Although you must still either explicitly compare an optional with nil or use optional binding to additionally extract its value (i.e. optionals are not implicitly converted into Boolean values), it's worth noting that Swift 2 has added the guard statement to help avoid the pyramid of doom when working with multiple optional values.

    In other words, your options now include explicitly checking for nil:

    if xyz != nil {
        // Do something with xyz
    }
    

    Optional binding:

    if let xyz = xyz {
        // Do something with xyz
        // (Note that we can reuse the same variable name)
    }
    

    And guard statements:

    guard let xyz = xyz else {
        // Handle failure and then exit this code block
        // e.g. by calling return, break, continue, or throw
        return
    }
    
    // Do something with xyz, which is now guaranteed to be non-nil
    

    Note how ordinary optional binding can lead to greater indentation when there is more than one optional value:

    if let abc = abc {
        if let xyz = xyz {
            // Do something with abc and xyz
        }        
    }
    

    You can avoid this nesting with guard statements:

    guard let abc = abc else {
        // Handle failure and then exit this code block
        return
    }
    
    guard let xyz = xyz else {
        // Handle failure and then exit this code block
        return
    }
    
    // Do something with abc and xyz
    
    0 讨论(0)
提交回复
热议问题