变量 num 更改为observeSingleEvent 中我想要的内容,但就在它变回空值之后。我如何改变 num 的值?
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
}
最佳答案
您需要对从 Firebase 返回的值执行的任何操作都必须在完成处理程序(方法调用的 with
部分)内完成。要使用/操作从 Firebase 获取的 num
值,您需要在完成处理程序中使用它。
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")
}
}
})
关于ios - 在observeSingleEvent 中变量的值没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53886052/