Iterate through Core Data with for loop?

Viewed 224

I'm trying to add all expenses that match a certain category in an expense tracker app.

        ForEach(fetchRequestExpense) { (expenselog: Expenses) in
                if category == expenselog.expenseCategory{
                    var sum += expenselog.expenseCost
                }
            }
        return sum
    }

This won't compile. Should I be using a for loop for this type of calculation?

2 Answers

The ForEach is a dynamic view container for constructing SwiftUI views, for control flow you have to use regular swift for/in, like

var sum = 0.0
for expenselog in fetchRequestExpense {
    if category == expenselog.expenseCategory {
        sum += expenselog.expenseCost
    }
}
return sum
Related