简体   繁体   中英

Correct syntax for reading value in nested array?

If anyone could help i'm having trouble with the syntax. What is the correct way to read an Int in an

Array -> Dict -> Array -> Dict -> Array -> [0]

I'm new to Swift 3 and am having trouble extracting the variable. Any help would be apreciated. I've tried something along the lines of:

let sen = dict["senzu"] as? [[String:Any]]
  let sen1 = dfa?[0][0]["green"] as? Any

To make it more clear, I divided:

Array -> Dict -> Array -> Dict -> Array -> [0]

to separated levels, assuming that the last array is level 05 and the first array is level 01, as follows:

// Array of Ints
var arrayLevel_05 = [1, 2, 3, 4]

// Dict of arrays of ints
var dictLevel_04: [String: [Int]] = ["myArray01": arrayLevel_05]

// Array of dicts of arrays of ints
var arrayLevel_03:[[String: [Int]]] = [dictLevel_04]

// Dict of arrays of dicts of arrays of ints
var dictLevel_02: [String: [[String: [Int]]]] = ["myArray02": arrayLevel_03]

// Array of dict of arrays of dicts of arrays of ints
var arrayLevel_01:[[String : [[String : [Int]]]]] = [dictLevel_02]

So, for getting the values of ints in arrayLevel_05 :

let one = arrayLevel_01[0]["myArray02"]?[0]["myArray01"]?[0]
let tow = arrayLevel_01[0]["myArray02"]?[0]["myArray01"]?[1]
let three = arrayLevel_01[0]["myArray02"]?[0]["myArray01"]?[2]

Note that they are optionals because you are reading values from dictionaries, if you are pretty sure that you will always get a value, you can replace the ? with ! (force unwrapping) as follows:

let one = arrayLevel_01[0]["myArray02"]![0]["myArray01"]![0]
let tow = arrayLevel_01[0]["myArray02"]![0]["myArray01"]![1]
let three = arrayLevel_01[0]["myArray02"]![0]["myArray01"]![2]

Or follow the optional binding approach:

if let arrayLevel03 = arrayLevel_01[0]["myArray02"], let arrayLevel05 = arrayLevel03[0]["myArray01"] {
    let one = arrayLevel05[0]   // 1
    let tow = arrayLevel05[1]   // 2
    let three = arrayLevel05[2] // 3
}

For more information about what are optionals, check Apple Documentation (Optional Section).

Hope this helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM