如何在Swift中的字典中安全地解包深层嵌套值?

时间:2018-02-28 20:18:46

标签: ios swift nsdictionary unwrap

我理解如何打印上层事物的价值,例如"电子邮件"或者" name"的值但是我如何安全地打开字典以打印更深层次的嵌套值,例如" url"?

的值

enter image description here

2 个答案:

答案 0 :(得分:2)

嵌套只意味着顶级[String: Any]字典中特定键的值是另一个[String: Any] - 因此您只需要将其强制转换为访问嵌套对象。

// assuming you have an object `json` of `[String: Any]`
if let pictureJSON = json["picture"] as? [String: Any] {
    // if the JSON is correct, this will have a string value. If not, this will be nil
    let nestedURL = pictureJSON["url"] as? String
}

我觉得我应该提一下,在Swift中序列化/反序列化JSON的过程在Swift 4中与Codable进行了一次重大飞跃。如果你有一个模型对象想要将这个JSON映射到,那么整个事情可以自动化away(包括嵌套对象 - 你只提供一个符合Codable的嵌套Swift结构/类)。 Here's some Apple documentation on it

答案 1 :(得分:0)

就像那样:

if let picture = dictionary["picture"] as? [String:AnyObject] {

        if let url = picture["url"] as? String {

        }

        if let width = picture["width"] as? Int {

        }

    }