Value of variable not changing in observeSingleEvent

瘦欲@ 提交于 2020-01-11 13:40:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!