james james - 1 year ago 154
Swift Question

Get data out of array of Firebase snapshots

I have an array of Firebase snapshots

var guardians: Array<FIRDataSnapshot> = []
. I'd like to access each snapshot's child value using a loop like this:

for snapshot in self.guardians{
let guardianID = (snapshot.value as? NSDictionary)?["guardian"] as? NSString

But I keep getting nil for guardianID. How can I get specific child values out of this array? For reference, here is what self.guardians prints to console:

[Snap (guardians) {
"-KQaU9lVcUYzIo52LgmN" = {
dependent = sJUCytVIWmX7CgmrypqNai8vGBg2;
guardian = jY2MtbIw4rQmgcZwTbLXNrL7tDq2;

I'm using Swift 3 with Xcode 8.


Jay Jay
Answer Source

I am not sure if the question can be answered without knowing how the array is built. One gotcha is the For-in loops variable is a NSFastEnumerationIterator so it needs to be downcast to what kind of 'thing' you want it to be. You may have done that so this is just for future reference.

That being said, I crafted up some code and broke it down a bit - maybe it will point you in the right direction.

The code below reads in all nodes by .value and then iterates over the snapshot and stores each child in an array as a FDataSnapshot. Then the code iterates over that array and prints the 'guardian' from each snapshot stored in the array.

I also included your code to print the guardianID and it works as well so my guess is the problem lies with how the array is being initially populated or in this line

for snapshot in self.guardians

as the snapshot is a NSFastEnumerationIterator

let ref = self.myRootRef.child(byAppendingPath: "guardian_node")!

ref.observe(.value, with: { snapshot in

     if ( snapshot!.value is NSNull ) {
          print("not found")
     } else {

          var guardianArray = [FDataSnapshot]()

          for child in snapshot!.children {
               let snap = child as! FDataSnapshot //downcast

          for child in guardianArray {
               let dict = child.value as! NSDictionary
               let thisGuardian = dict["guardian"]!

               //your code
               let guardianID = (child.value as? NSDictionary)?["guardian"] as? NSString

*This is Swift 3 and Firebase 2.x but the concept is the same.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download