accessing nested dictionary from api in swift

余生长醉 提交于 2019-12-04 17:41:58

Assuming data is NSDictionary, or [String:AnyObject]. You can:

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

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

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".

If you are wanting the syntax you described, I'd suggest using SwiftyJSON. It seems pretty popular, and it's all implemented in a single swift file so not hard to add it to your project. It would look something like this.

let floorPlanSummary = JSON(data: yourRawData)
self.beds = floorPlanSummery["bedrooms"]["formatted"].string

You may be able to just invoke data.valueForKeyPath("floorplan_summary.bedrooms.formatted")

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!