问题描述
圣牛...必须 是访问
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?
如何简化呢?
推荐答案
假定data
是NSDictionary
或[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访问嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!