senty senty - 6 months ago 15
Swift Question

Getting keys of multidimensional array (of `[String: [String: String]]`)

I have a multidimensional array with structure

[String: [String: String]]
. I am able to reach the
[String: String]
bit with a for loop, but I couldn't figure out how to access to the main keys (this bit
[String: [
).

let items = snapshot.value as! [String: [String: String]]

for item in items.values {
if let from = item["from"] {
self.users.append(from) // this works
}
}


How can I reach the main id of this node?

The node looks like this:

- table
- "1"
- "from": "AA"
- "to": "BB"
- "2"
- "from": "AA"
- "to": "BB"


I am trying to get
var array = ["1", "2", "3"]

Answer

use a Tuple will be clear try this :

let dict = ["1":["from":"aa","to":"bb"],"2":["from":"AA","to":"BB"]]

var array = [String]()
for (_ ,value) in dict{
    if let v = value["from"] {
        array.append(v)
    }
}
print(array)

update:

let keys = dict.keys.flatMap({$0})

print(keys)