Value of variable not changing in observeSingleEve

2019-03-03 13:29发布

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条回答
家丑人穷心不美
2楼-- · 2019-03-03 13:51

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")
        }
    }
})
查看更多
登录 后发表回答