Pascal Friedrich Pascal Friedrich - 28 days ago 21
Swift Question

Why getting nil when iterating through firebase database?

I'm struggling with my firebase db and i don't know, what i'm doing wrong.

self.ref.child("User").observeSingleEvent(of: .value, with: { (snapshot) in

let value = snapshot.value as! [String: AnyObject]

for each in value {
let username = each.value["username"] as! String
self.ref.child("Highscores").child(username).observeSingleEvent(of: .value, with: { (snapshot) in
let wert = snapshot.value as! [String: AnyObject]
for each in wert {
let fbscore = each.value["score"] as! String


In this case, fbscore is nil.

The output (print) of each is ("score", 21), so each.key is "score" and each.value is "21".

Where is my mistake? I didn't see anything.

Thank you very much for your help!

Pascal

Answer

You need to Downcast AnyObject to correct type Int not String.

each.value as! Int

As well as to prevent nil exceptions.Use guard or optional Binding.

if let fbscore = each.value as? Int {      
    print(fbscore)
}else{
   print("casting failed")
}