Guys, I need to return the Int value obtained from the database, but since Firebase does the asynchronous method for me, the value returns zero. Can anyone suggest how you can change this block of code?

func blueRewardPercent() -> Int { let userRef = FIRAuth.auth()?.currentUser?.uid var rewardPercent : Int = 0 let purchaseRef = FIRDatabase.database().reference(withPath: "Reward/\(userRef!)") purchaseRef.queryOrdered(byChild: "systemLastLogin").observe(.value, with: { snapshot in let dataSnapshot = snapshot.value as! [String: AnyObject] rewardPercent = dataSnapshot["rewardCardPercent"] as! Int! // Здесь нужно сделать return }) return rewardPercent } 

    1 answer 1

    That's right, rewardPercent you return before you receive the data. Change, for example, like this:

     func blueRewardPercent(completion: @escaping (Int) -> ()) { let userRef = FIRAuth.auth()?.currentUser?.uid var rewardPercent : Int = 0 let purchaseRef = FIRDatabase.database().reference(withPath: "Reward/\(userRef!)") purchaseRef.queryOrdered(byChild: "systemLastLogin").observe(.value, with: { snapshot in let dataSnapshot = snapshot.value as! [String: AnyObject] rewardPercent = dataSnapshot["rewardCardPercent"] as! Int! // Здесь нужно сделать return completion(rewardPercent) }) } 

    and apply:

     blueRewardPercent { (rewardPercent) in print(rewardPercent) }