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

问题描述 投票:-1回答:2

我理解如何打印上层事物的值,例如“email”的值或“name”的值,但是如何安全地打开字典以打印更深层次的嵌套值,例如“url”的值?

enter image description here

ios swift nsdictionary unwrap
2个回答
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映射到,那么整个事情可以自动化(包括嵌套对象 - 您只需提供符合Codable的嵌套Swift结构/类。 Here's some Apple documentation on it


0
投票

像那样:

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

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

        }

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

        }

    }
© www.soinside.com 2019 - 2024. All rights reserved.