快速从api访问嵌套字典

快速从api访问嵌套字典

本文介绍了快速从api访问嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

圣牛...必须 是访问

floorplan_summary: {
    bedrooms: {
        low: 1,
        high: 2,
        formatted: "1 - 2 Beds"
    }
}

比这样做:

    if data["floorplan_summary"]?["bedrooms"] != nil {
        let bedrooms = data["floorplan_summary"]?["bedrooms"] as NSDictionary
        if bedrooms["formatted"] != nil{
            self.beds = bedrooms["formatted"] as String
        }
    }

我只想这样做:

self.beds = data["floorplan_summary"]?["bedrooms"]?["formatted"] as String

..但是在每个级别,对象似乎都被强制转换为AnyObject.为什么编译器可以假定此data["floorplan_summary"]?["bedrooms"]而不是上面的?

..but at each level the object seems to be cast as AnyObject. Why can the compiler assume this data["floorplan_summary"]?["bedrooms"] but not the above?

如何简化呢?

推荐答案

假定dataNSDictionary[String:AnyObject].您可以:

let beds = data["floorplan_summary"]?["bedrooms"]??["formatted"] as? String // -> as String?
                                                  ^

您需要额外的?,因为data["floorplan_summary"]?["bedrooms"]返回AnyObject??.您必须两次将其解包.

You need extra ? because data["floorplan_summary"]?["bedrooms"] returns AnyObject??. You have to unwrap it twice.

为什么返回AnyObject???因为data["floorplan_summary"]?AnyObject,并且AnyObject 可能具有subscript.因此,第一个?表示如果它具有subscript",第二个表示如果subscript返回非nil".

Why it returns AnyObject??? Because data["floorplan_summary"]? is AnyObject, and AnyObject may or may not have subscript. So, the first ? means, "If it has subscript", and the second means "If subscript returns non nil".

这篇关于快速从api访问嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 16:28