问题
The variable num changes to what I want inside the observeSingleEvent, but just after it changes back to an empty value. How do i get the value of num to change??
var num = Int()
FIRDatabase.database().reference().child("menus/Day1").observeSingleEvent(of: .value, with: {(snap) in
print(snap)
if let snapDict = snap.value as? [String:AnyObject]{
self.num = snapDict["date"] as! Int
print(num)
//returns the number I want
}
})
print(num)
//Returns an empty value
if num == 5 {
print("number is 5")
else {
print("number is not 5")
//goes to this
}
回答1:
Any work that you need to do with values that are coming back from Firebase must be done within the completion handler (the with part of the method call). To use/manipulate the num value you get from Firebase, you need to use it within your completion handler.
var num = Int()
FIRDatabase.database().reference().child("menus/Day1").observeSingleEvent(of: .value, with: {(snap) in
print(snap)
if let snapDict = snap.value as? [String:AnyObject]{
self.num = snapDict["date"] as! Int
if self.num == 5 {
print("number is 5")
else {
print("number is not 5")
}
}
})
来源:https://stackoverflow.com/questions/43071594/value-of-variable-not-changing-in-observesingleevent