【问题标题】:Swift access fields in nested dictionary嵌套字典中的快速访问字段
【发布时间】:2016-01-20 11:05:55
【问题描述】:

我必须处理这样的字典,或者更多嵌套。 如何访问“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["fieldThree"]["twoTwo"]吗?
  • 嵌套Dict["fieldThree"][0][0]["twoTwo"]之间有一些数组会失败

标签: ios swift dictionary nested


【解决方案1】:

nestedDict 是一个Dictionary,你得到fieldThree

let fieldThree = nestedDict["fieldThree"] as! [[String:Any]] // [[String:AnyObject]] in Swift 2 and lower.

fieldThree 是Arrayof [String:AnyObject] 字典,您将获得第一个数组项的twoTwo 的值

let twoTwo = fieldThree[0]["twoTwo"] as! Bool

您甚至可以检索数组中键 twoTwo 的所有值

let allTwoTwo = fieldThree.map { $0["twoTwo"] as! Bool }

【讨论】:

    猜你喜欢
    • 2020-06-01
    • 2015-10-31
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 2020-12-31
    • 2023-04-04
    相关资源
    最近更新 更多