Swift 访问嵌套字典中的字段
Swift access fields in nested dictionary
我必须处理像这样或更多嵌套的字典。
如何访问 "twotwo" 之类的字段?或者有没有更好的可能性来模拟这种结构?
let nestedDict = [
"fieldOne": "name",
"fieldTwo": "name",
"fieldThree":
[
[
"twoOne": "some text",
"twoTwo": true,
"twoThree": 1e-40
],
[
"twoOne": "some text",
"twoTwo": true,
"twoThree": 1e-40
]
]
]
nestedDict
是 Dictionary
,你得到 fieldThree
和
let fieldThree = nestedDict["fieldThree"] as! [[String:Any]] // [[String:AnyObject]] in Swift 2 and lower.
fieldThree
是 Array
个 [String:AnyObject]
字典,你得到第一个数组项 twoTwo
的值
let twoTwo = fieldThree[0]["twoTwo"] as! Bool
您甚至可以检索数组中键 twoTwo
的所有值
let allTwoTwo = fieldThree.map { [=12=]["twoTwo"] as! Bool }
我必须处理像这样或更多嵌套的字典。 如何访问 "twotwo" 之类的字段?或者有没有更好的可能性来模拟这种结构?
let nestedDict = [
"fieldOne": "name",
"fieldTwo": "name",
"fieldThree":
[
[
"twoOne": "some text",
"twoTwo": true,
"twoThree": 1e-40
],
[
"twoOne": "some text",
"twoTwo": true,
"twoThree": 1e-40
]
]
]
nestedDict
是 Dictionary
,你得到 fieldThree
和
let fieldThree = nestedDict["fieldThree"] as! [[String:Any]] // [[String:AnyObject]] in Swift 2 and lower.
fieldThree
是 Array
个 [String:AnyObject]
字典,你得到第一个数组项 twoTwo
的值
let twoTwo = fieldThree[0]["twoTwo"] as! Bool
您甚至可以检索数组中键 twoTwo
的所有值
let allTwoTwo = fieldThree.map { [=12=]["twoTwo"] as! Bool }