简体   繁体   English

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

[英]How can I safely unwrap deeply nested values in a dictionary in Swift?

I understand how to print the values of upper level things such as the value of "email" or the value of "name" but how would I safely unwrap the dictionary to print a deeper nested value such as the value of "url"? 我知道如何打印上层内容的值,例如“电子邮件”的值或“名称”的值,但是我将如何安全地展开字典以打印更深层的嵌套值(例如“ url”的值)?

在此处输入图片说明

Nesting just means that the value for a particular key in your top level [String: Any] dictionary is another [String: Any] - so you just need to cast it to access nested objects. 嵌套只是意味着顶级[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
}

I feel I should mention that the process of serializing/de-serializing JSON in Swift took a big leap with Codable in Swift 4. If you have a model object you want to map this JSON to, this whole thing can be automated away (including nested objects - you just supply a nested Swift struct/class conforming to Codable). 我觉得我应该提到,Swift中的JSON序列化/反序列化过程与Swift 4中的Codable相比有了很大的飞跃。如果您有想要将此JSON映射到的模型对象,则整个过程可以自动化处理(包括嵌套对象-您只提供符合Codable的嵌套Swift结构/类)。 Here's some Apple documentation on it . 这是关于它的一些Apple文档

Like that: 像那样:

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

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

        }

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

        }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM