Swift Hipster Swift Hipster - 3 months ago 7
Swift Question

Swift optional nil check returns different result than actual case

is a dictionary. When I check
for nil value. It says it is not nil. But when I unwraps it actually contains null value. Here is my debugger output. How is this possible?

Debugger output


po taker["user_id"] gives you the correct answer: Some: <null> means that what's inside the nullable value is null. Even without Foundation interop, you could get something similar with a dictionary of optional values (like [Int: Int?]).

In your case, though, it's "just" that the object in the optional is an instance of NSNull(). NSNull is a special type that you use in places where nil would not be acceptable. For instance, Objective-C NSDictionaries do not support nil values (as they return nil for keys that are absent in the dictionary). If you want to signal that a NSDictionary key exists but has no value, the most common thing to do is to associate it to a NSNull value.

I suspect that taker is a dictionary derived from JSON. You should check that, additionally to the key being present, the value has the type that you expect. This will weed out NSNulls and possibly other incorrect inputs. For instance:

if let value = taker["user_id"] as? Int {
    // things here