1

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"]

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I am trying have array as array = ["1","2"] etc. "from" bit is working fine. Do you have any suggestion?
0

For arrays like that, where you have key->value pairs, you can access the key value as the element .0, and the value as element .1

Try this in a playground and see if it flies:

for firstLevel in tableArray {
    print(firstLevel.0)
    for innerLevel in firstLevel.1 {
        print(innerLevel.0)
        print(innerLevel.1)
    }
    print("\n")
}

1 Comment

This also works but other answer is more right. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.