ios - 在observeSingleEvent 中变量的值没有改变

标签 ios swift firebase swift3 firebase-realtime-database

变量 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/

相关文章:

objective-c - UITextView:键入退格键时,字符计数不正确

swift - 类型 'Any' 没有下标成员

ios - Swift Facebook 登录崩溃

ios - 为什么 EmptyView() 不能在带有 SwiftUI 的 WatchOS 上运行?

iphone - 无法识别的选择器发送到 OAuthCore 类中的类

ios - 如何使用 decodable 正确解码此 json 字符串?

java - Android 中 user.sendEmailVerification() 上没有虚拟方法 sendEmailVerification() 异常

javascript - onSubmit 方法在使用 Firebase 的 React 中执行渲染

java - 如何从 Firestore 中的集合中检索所有文档?

ios - 如何在自签名证书上使用 Socket-IO-Swift 进行连接?