Swift Hipster Swift Hipster - 1 year ago 90
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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download