有关NSDictionary和valueForKey的可选的Swift说明

时间:2015-03-16 18:59:36

标签: ios swift nsdictionary optional

我试图学习Swift移植管理HttpRequest的Obj-C代码,但是当我收到JSON中的响应时,我试图访问NSDictionary。

JSON示例:

{
    response =     {
        id = 1234;
        name = a2b3n4h5lkl3;
    };
}

我从HttpRequest completionHandler

收到
(dictionary:NSDictionary?, error:NSError?) -> Void

比我想从NSDictionary获得一些值?并将它们保存到var:

let responseDictionary = dictionary!.valueForKey("response") as? NSDictionary

println(responseDictionary!)                        // The informations are present correctly

if (responseDictionary!.count > 0) {

    var testStringAccessId:NSString? = responseDictionary!.valueForKey("id")! as? NSString

    println(testStringAccessId)                     // print nil

    println(responseDictionary!.valueForKey("id")!) // print the correct value

    if let stringAccessId = responseDictionary!.valueForKey("id")! as? NSString {
        self.accessID = stringAccessId
    } else {
        println("Error No Access ID")               // Enter here
        completion(success: false)
        return                                      // The function exit with error
    }
}

我尝试了很多组合,但也许我在可选用途中遗漏了一些东西。奇怪的是,如果我在错误情况下评论返回并尝试从NSDictionary中获取另一个值,那么这个是正确的,例如:

if let stringAccessNAME = responseDictionary!.valueForKey("name")! as? NSString {
    self.accessNAME = stringAccessNAME              // I get the correct value saved in the variable
} else {
    println("Error No Access NAME")
    completion(success: false)
    return
}

请帮忙吗?

由于 麦酒

解决

使用NSNumber而不是NSString。感谢Jesper

1 个答案:

答案 0 :(得分:0)

正如您在编辑后在问题中正确陈述的那样,您的ID不存储为字符串(或NSString),尝试将字符串强制转换为NSNumber将返回值为nil。

var testStringAccessId:NSNumber? = responseDictionary!.valueForKey("id")! as? NSNumber

这是在这里使用的正确语法。

我可能想补充一点,你在检查之前解开字典。您可能想在那里添加一个检查,如果您无法连接到互联网,或者当您的API崩溃时会发生什么?您很少需要使用!