Swift: Testing optionals for nil

前端 未结 14 676
攒了一身酷
攒了一身酷 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.

提交回复
热议问题