检测NSDictionary中的Null值 [英] Detect a Null value in NSDictionary

查看:249
本文介绍了检测NSDictionary中的Null值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSDictionary ,它来自API服务器的JSON响应。有时这个字典中的键的值是 Null

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.

问题是,当我尝试将值强制转换为 NSString 时,我遇到了崩溃,我 think 是因为我试图将 Null 强制转换为字符串。

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 I want to do is something like this:

cell.detailTextLabel.text = sensor.objectForKey( "latestValue" ) as NSString

以下是字典的示例:

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";
}

如果我只需要在条件中包装所有这些,那很好。我只是无法弄清楚条件是什么。回到Objective-C世界,我会与 [NSNull null] 进行比较,但这似乎不适用于Swift。

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.

推荐答案

您可以使用作为?运算符,它返回一个可选值( nil 如果downcast失败了)

You can use the as? operator, which returns an optional value (nil if the downcast fails)

if let latestValue = sensor["latestValue"] as? String {
    cell.detailTextLabel.text = latestValue
}

我测试了这个swift应用程序中的示例

I tested this example in a swift application

let x: AnyObject = NSNull()
if let y = x as? String {
    println("I should never be printed: \(y)")
} else {
    println("Yay")
}

并正确打印Yay,而

let x: AnyObject = "hello!"
if let y = x as? String {
    println(y)
} else {
    println("I should never be printed")
}

按预期打印你好!

这篇关于检测NSDictionary中的Null值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆