【问题标题】:How can I safely unwrap deeply nested values in a dictionary in Swift?如何在 Swift 的字典中安全地展开深度嵌套的值?
【发布时间】:2018-02-28 20:18:46
【问题描述】:

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

【问题讨论】:

  • 将字典解析成适当的 Codable 结构。
  • 请将代码发布为文本而不是照片,这样人们可以直接将您的代码复制到游乐场并进行测试。

标签: ios swift nsdictionary unwrap


【解决方案1】:

嵌套只是意味着您的顶级 [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.

【讨论】:

    【解决方案2】:

    这样:

    if let picture = dictionary["picture"] as? [String:AnyObject] {
    
            if let url = picture["url"] as? String {
    
            }
    
            if let width = picture["width"] as? Int {
    
            }
    
        }
    

    【讨论】:

    • Swift 本机字典值类型为Any。大多数 Swift 类型都是结构。 AnyObject 只能用作类实例的具体类型。
    • 我同意这一点,但是这个例子来自一个 Firebase 获取方法,推荐使用 AnyObject。
    猜你喜欢
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 2021-12-29
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 2018-10-21
    相关资源
    最近更新 更多