Swift: Testing optionals for nil Swift: Testing optionals for nil ios ios

Swift: Testing optionals for nil


In Xcode Beta 5, they no longer let you do:

var xyz : NSString?if xyz {  // Do something using `xyz`.}

This produces an error:

does not conform to protocol 'BooleanType.Protocol'

You have to use one of these forms:

if xyz != nil {   // Do something using `xyz`.}if let xy = xyz {   // Do something using `xy`.}


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

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

you can reuse the same variable name like this:

var a: Int? = 5if 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.


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.