Markus Frindt
Markus Frindt

Reputation: 11

Swift access fields in nested dictionary

I've got to deal with a Dictionary like this, or more nested. How can I access fields like "twotwo" ? Or is there any better possibility to model such structure?

let nestedDict = [
    "fieldOne": "name",
    "fieldTwo": "name",
    "fieldThree":
        [
            [
            "twoOne": "some text",
            "twoTwo": true,
            "twoThree": 1e-40
            ],
            [
            "twoOne": "some text",
            "twoTwo": true,
            "twoThree": 1e-40
            ]
        ]
]

Upvotes: 1

Views: 632

Answers (1)

vadian
vadian

Reputation: 285069

nestedDict is a Dictionary, you get fieldThree with

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

fieldThree is an Arrayof [String:AnyObject] dictionaries, you get the value of twoTwo of the first array item with

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

You can even retrieve all values of key twoTwo in the array

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

Upvotes: 3

Related Questions