Tian Xi Tian Xi - 7 days ago 4
Swift Question

Firebase - retrieve all child keys and child values into separate arrays in Swift

Is there any way to retrieve all the keys in a child, put them into array, and then retrieve the values for the keys and put it into another array?

Source code:

self.ref?.child("data").child("success").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot != nil {
// Your answer goes here

Jay Jay

Snapshots have two properties.


When using an observer with .value. all of the key: value children are returned in the snapshot. They can be iterated over to capture each key: value pair like this.

ref.observeSingleEvent(of: .value, with: { (snapshot) in
    for child in snapshot.children {
        let snap = child as! DataSnapshot
        let key = snap.key
        let value = snap.value
        print("key = \(key)  value = \(value!)")

Keep in mind that the value property could be a string, number, array or another dictionary (snapshot). In the original question it's a String.