I have an NSDictionary
that's populated from a JSON response from an API server. Sometimes the values for a key in this dictionary are Null
I am trying to take the given value and drop it into the detail text of a table cell for display.
The problem is that when I try to coerce the value into an NSString
I get a crash, which I think is because I'm trying to coerce Null
into a string.
What's the right way to do this?
What I want to do is something like this:
cell.detailTextLabel.text = sensor.objectForKey( "latestValue" ) as NSString
Here's an example of the Dictionary:
Printing description of sensor:
{
"created_at" = "2012-10-10T22:19:50.501-07:00";
desc = "<null>";
id = 2;
"latest_value" = "<null>";
name = "AC Vent Temp";
"sensor_type" = temp;
slug = "ac-vent-temp";
"updated_at" = "2013-11-17T15:34:27.495-07:00";
}
If I just need to wrap all of this in a conditional, that's fine. I just haven't been able to figure out what that conditional is. Back in the Objective-C world I would compare against [NSNull null]
but that doesn't seem to be working in Swift.
NSNull is a class like any other. Thus you can use
is
oras
to test an AnyObject reference against it.Thus, here in one of my apps I have an NSArray where every entry is either a Card or NSNull (because you can't put nil in an NSArray). I fetch the NSArray as an Array and cycle through it, switching on which kind of object I get:
That is not identical to your scenario, but it is from a working app converted to Swift, and illustrates the full general technique.
I had a very similar problem and solved it with casting to the correct type of the original NSDictionary value. If your service returns a mixed type JSON object like this
you'll have to fetch it's values like that.
This did solve my problem. See BAD_INSTRUCTION within swift closure
my solution for now:
tests look good so far...
I'm using those combination. Additionaly that combination checks if object is not
"null"
.It's not that pretty as extension but work as charm :)
You can use the
as?
operator, which returns an optional value (nil
if the downcast fails)I tested this example in a swift application
and it correctly prints
"Yay"
, whereasprints
"hello!"
as expected.You could also use
is
to check for the presence of a null: