首页 文章

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

提问于
浏览
0

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

JSON示例:

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

我从HttpRequest completionHandler收到

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

我希望从NSDictionary得到一些 Value ?并将它们保存到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
}

有什么帮助吗?

谢谢啤酒

SOLVED

使用NSNumber而不是NSString . 感谢Jesper

1 回答

  • 0

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

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

    这是在此处使用的正确语法 .

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

相关问题