Reputation: 301
I'm having a hard time with Firebase values in return functions. This seems to be an ongoing problem for me. I have written up a basic example of my issue. How do I go about doing this?
func getChartIndexValues(completion:@escaping (Double) -> ()) {
//Firebase Initialization
var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
ref.child("general_room_index").observeSingleEvent(of: .value, with: {(snapshot) in
let snapDict = snapshot.value as? NSDictionary
var zero = snapDict?["0"] as! Double
completion(zero)
})
}
returnFunction() -> (Double) {
getChartIndexValues() { (zero) -> () in
let testValue = zero
}
return //THis is my problem
}
Upvotes: 2
Views: 546
Reputation: 131408
You've hinted at your problem, but not stated it explicitly. The deal is that you can't return the result of an async function as a function result. You need to pass in a completion handler that runs when the function finishes, and that code is the code that has access to the result.
returnFunction() -> (Double) {
getChartIndexValues() { (zero) -> () in
//Your code to process the results belongs here
self.someInstanceVar = zero
someLabel.text = "Your result is \(zero)"
}
}
//You CAN'T put your code to process results here.
Upvotes: 1