Put it simply, I am trying to have a very basic function that takes a user ID and returns the associated balance to that user from a Firestore collection of users.
However, I am getting the following error:
"Variable 'newBalance' captured by a closure before being initialized"
The code is:
func getBalance(uid: String) -> Double {
var newBalance: Double
FirebaseManager.shared.firestore.collection("users").document(uid).getDocument{ snapshot, error in
guard let data = snapshot?.data() else {self.errorMessage = "No data found"
return}
let balance = data["balance"] as? Double ?? 0
print("Function balance \(balance)")
newBalance = balance
}
return newBalance
}
Any help would be appreciated! Thank you!
CodePudding user response:
You need a completion
func getBalance(uid: String,completion:@escaping(Double) -> ()) {
FirebaseManager.shared.firestore.collection("users").document(uid).getDocument{ snapshot, error in
guard let data = snapshot?.data() else {self.errorMessage = "No data found"
return}
let balance = data["balance"] as? Double ?? 0
print("Function balance \(balance)")
completion(balance)
}
}
Call
getBalance(uid:<#value#>) { balance in
print(balance)
}
OR with SwiftUI use @published
@published var newBalance: Double?
func getBalance(uid: String) {
FirebaseManager.shared.firestore.collection("users").document(uid).getDocument{ snapshot, error in
guard let data = snapshot?.data() else {self.errorMessage = "No data found"
return}
let balance = data["balance"] as? Double ?? 0
print("Function balance \(balance)")
self.newBalance = balance
}
}