I have an array of Firebase snapshots var guardians: Array
. I\'d like to access each snapshot\'s child value using a loop like this:
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
guardianArray.append(snap)
}
for child in guardianArray {
let dict = child.value as! NSDictionary
let thisGuardian = dict["guardian"]!
print(thisGuardian)
//your code
let guardianID = (child.value as? NSDictionary)?["guardian"] as? NSString
print(guardianID!)
}
}
})
*This is Swift 3 and Firebase 2.x but the concept is the same.