0

This question is not duplciated because others don't work and are not exactly like mine. I want to set the value of this snapshot in the var averageMark. Like in this code:

func initAverageMark(completion: @escaping (Bool) -> ()) {

    let userRef = ref.child("users").child((user?.uid)!).child("mark")

    userRef.observeSingleEvent(of: .value, with: { (snapshot) -> Void in
        if let mark: Double = snapshot.value as? Double {
            self.averageMark = mark
        }
        print("res: \(self.averageMark)") // 1st print
        completion(true)

    }) { (error) in
        print(error.localizedDescription)
    }
    print("res: \(self.averageMark)") // 2nd print
}

My issue is that the variable get a value inside the snapshot function but is nil outside of this function. The first print is "2.0" (which is correct) and the second is nil.

The real trouble is that I alreay did soemthing like that without any problem...

How is it possible? We can only use the values inside the snapshot? Thanks

Paul Bénéteau
  • 775
  • 2
  • 12
  • 36

0 Answers0