Swift: Testing optionals for nil

tng picture tng · Aug 2, 2014 · Viewed 172.6k times · Source

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 way to test:

if (xyz) // Do something

or

if (xyz != nil) // Do something

The documents say to do it the first way, but I've found that sometimes, the second way is required, and doesn't generate a compiler error, but other times, the second way generates a compiler error.

My specific example is using the GData XML parser bridged to swift:

let xml = GDataXMLDocument(
    XMLString: responseBody,
    options: 0,
    error: &xmlError);

if (xmlError != nil)

Here, if I just did:

if xmlError

it would always return true. However, if I do:

if (xmlError != nil)

then it works (as how it works in Objective-C).

Is there something with the GData XML and the way it treats optionals that I am missing?

Answer

ktzhang picture ktzhang · Aug 8, 2014

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`.
}