2

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 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

Normally you would use an @sum fetch request and dictionary result type:

https://developer.apple.com/documentation/coredata/nsfetchrequestresulttype/1506237-dictionaryresulttype

See this similar question:

Core Data sum of all instances attribute

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.