user7780338
user7780338

Reputation: 1

Value of variable not changing in observeSingleEvent

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
     }

Upvotes: 0

Views: 226

Answers (1)

dst3p
dst3p

Reputation: 1038

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")
        }
    }
})

Upvotes: 1

Related Questions