dfucci dfucci - 1 month ago 13
Swift Question

Iterate over snapshot children in Swift (Firebase)

I have a Firebase resource that contains several objects and I would like to iterate over them using Swift.
What I expected to work is the following (according to the Firebase documentation)

https://www.firebase.com/docs/ios-api/Classes/FDataSnapshot.html#//api/name/children

var ref = Firebase(url:MY_FIREBASE_URL)
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
println(snapshot.childrenCount) // I got the expected number of items
for rest in snapshot.children { //ERROR: "NSEnumerator" does not have a member named "Generator"
println(rest.value)
}
})


So it seems there is a problem with Swift iterating over the NSEnumerator object returned by Firebase.

Help is really welcome.

Answer

If I read the documentation right, this is what you want:

var ref = Firebase(url:MY_FIREBASE_URL)
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
    println(snapshot.childrenCount) // I got the expected number of items
    for rest in snapshot.children.allObjects as [FDataSnapshot] {
       println(rest.value)     
    }
})

A better way might be:

var ref = Firebase(url:MY_FIREBASE_URL)
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
    println(snapshot.childrenCount) // I got the expected number of items
    let enumerator = snapshot.children
    while let rest = enumerator.nextObject() as? FDataSnapshot {
       println(rest.value)     
    }
})

The first method requires the NSEnumerator to return an array of all of the objects which can then be enumerated in the usual way. The second method gets the objects one at a time from the NSEnumerator and is likely more efficient.

In either case, the objects being enumerated are FDataSnapshot objects, so you need the casts so that you can access the value property.