The original function is meant to look like this:
func retrieveMonthlySpent(month:String, year:String) -> Double {
FirebaseFunctions().retrieve(from: .expense, username: self.username as! String, returning: Expenses.self) { (expenses) in
self.monthlyExpenses = expenses
}
var sum:Double = 0
for expense in self.monthlyExpenses{
if expense.modificationDate.convertToMonth() == month && expense.expense && expense.modificationDate.convertToYear() == year {
sum += expense.convertedAmount
}
}
return sum
}
But then the monthly expenses value wouldn't be updated because of the way sync functions work in Swift. So then I tried to change my code so that I put as much code into the async function itself and it looked like this:
func retrieveMonthlySpent(month:String, year:String) -> Double{
FirebaseFunctions().retrieve(from: .expense, username: self.username as! String, returning: Expenses.self) { (expenses) in
self.monthlyExpenses = expenses
var sum:Double = 0
for expense in self.monthlyExpenses{
if expense.modificationDate.convertToMonth() == month && expense.expense && expense.modificationDate.convertToYear() == year{
sum += expense.convertedAmount
}
}
}
return sum
}
But the problem is that now the value of "sum" is 0 because I use a variable outside this async function. I have seen the issue been raised on multiple questions but I can't find an answer anywhere. What is the solution to this problem