在从NSDictionary获取值时展开可选值时出乎意料地发现了nil

时间:2015-01-20 16:39:39

标签: ios json swift nsdictionary

我正在尝试从NSDictionary获取值,但这里有两个地方,EXC_BAD_INSTRUCTION有致命错误。 我很有兴趣如何在没有这个问题的情况下从NSDictionary获取值

private func checkResponseResult(responseResult: NSDictionary) {

    // Initialize Group object and [Group] arrays
    println(responseResult)

    for item in responseResult {

        //create object of Group, set attributes, add to Array

        var itemKey = item.key as NSString

        if itemKey.isEqualToString("error") {

            // Error received, user has no groups assigned

            println("Error: \(item.value)")
        } else {

            // Groups values received

            println("Core Data insert / group id: \(item.key)")
            var gr:Group = Group()

            var name = "name"
            var latitude = "latitude"
            var longitude = "longitude"
            var project = "project"
            var radius = "raidus"

            var val = item.value[longitude]
            //return nil
            println(val)
           //return false
           println(val==nil)

            gr.id = itemKey.integerValue
            gr.name = item.value[name] as String
            gr.latitude = item.value[latitude] == nil || item.value[latitude] as NSNull == NSNull() ? 0.0 : item.value[latitude] as NSNumber

           //fatal error: unexpectedly found nil while unwrapping an Optional value
            gr.longitude = item.value[longitude] == nil || item.value[longitude] as NSNull == NSNull() ? 0.0 : item.value[longitude] as NSNumber

            gr.project = item.value[project] as String

            //fatal error: unexpectedly found nil while unwrapping an Optional value
            gr.radius = item.value[radius] == nil || item.value[radius] as NSNull == NSNull() ? 0.0 : item.value[radius] as NSNumber

        }

    }

}  

NSDictionary就在这里

{
30 =     {
    latitude = "<null>";
    longtitude = "<null>";
    name = mtmb;
    project = "pr_mtmb";
    radius = "<null>";
};
}

2 个答案:

答案 0 :(得分:0)

这&#34; item.value[latitude] == nil || item.value[latitude] as NSNull == NSNull()&#34;这是过度杀戮,这是旧的做法,我认为展开价值来检查NSNull是导致崩溃的原因,创造了一个Catch-22。无论如何,使用Swift选项更好的方式,&#34;如果让&#34;:

if let checkedLongitude = item.value[longitude] {
    gr.longitude = checkedLongitude
} else {
    gr.longitude = 0.0 as NSNumber
}

您无法使用? :短版本执行此操作,该版本仅适用于最简单的if-then,无论如何。

答案 1 :(得分:0)

您有两个拼写错误,一个在您的词典中,另一个在您的密钥中:

30 =     {
    latitude = "<null>";
    **longtitude** = "<null>";
    name = mtmb;
    project = "pr_mtmb";
    **radius** = "<null>";
};

然后

var longitude = "longitude"
var radius = "raidus"
gr.longitude = item.value[longitude] == nil || item.value[longitude] as NSNull == NSNull() ? 0.0 : item.value[longitude] as NSNumber
gr.radius = item.value[radius] == nil || item.value[radius] as NSNull == NSNull() ? 0.0 : item.value[radius] as NSNumber