I was working on a new page in one of my apps and was facing a small issue involving Firebase and While Loops. Below is my code:
var user = User()
var i = 0
while i < 101 {
print("Print Statement 1: " + String(i))
//Correctly prints i, incrementing it by 1 every time like it should.
self.ref.child("Directory")
.child(String(i))
.observeSingleEvent(of: .value, with: { (snapshot) in
print("Print Statement 2: " + String(i))
//Always prints 101
let nameValue = snapshot.value as? NSDictionary
if nameValue != nil {
user.id = String(i)
//Always get set to 101, and not the current value of i
}
}) { (error) in
print(error.localizedDescription)
}
i += 1
}
Logs:
Print Statement 1 :
0
1
2
3
4
etc.
Print Statement 2:
101
101
101
101
101
etc.
Pretty much the only question I have here is why is the second print statement always printing 101 and not the incremented value of i. Is this something related to the Firebase Observer not observing the single event every time the while loop is executed? Also, what can I do to fix this?
Thanks, KPS