I cant seem to understand why this can throw an error? The first for each loop is working perfectly, 2nd is throwing an error. I need to use index of the array to get custom colors for my code. Otherwise i would go with normal ForEach.
@ViewBuilder
private func chartLegendView() -> some View {
if !viewModel.topTransactions.isEmpty {
VStack {
ForEach(viewModel.topTransactions, id: \.self) { transaction in
Text(transaction.description)
}
ForEach(viewModel.topTransactions.indices, id: \.self) { index in
Text(viewModel.topTransactions[index].description)
}
}
}
}
I have tried all the logical options, but nothing works.
UPDATE 1: This is what I am trying to achieve. Im getting an array of transactions from SwiftData. I am creating a custom object from that array of transactions (grouping by category and some other calculations) and displaying them in a SwiftUI Chart. What I have is that my Chart legend and Chart colors are custom.
I have predefined 10 colors to be used on the chart in an array. That's why I use an index to grab a color from each item In the chart.
My user can choose "Income, Expense, or date" to filter the data coming from SwiftData and regenerate the UI. I do agree that the problem looks like a model/fetching issue.
this is how I have "solved" the problem, but its wrong. I still have crashes when filters change.
@ViewBuilder
private func chartLegendView() -> some View {
VStack {
ForEach(Array(viewModel.topTransactions.prefix(analyticsTransactionsNumber).enumerated()), id: \.element) { index, transaction in
TopExpenseRow(topExpense: transaction, color: categoryColors[index])
}
}
}
struct TopTransaction: Comparable, Hashable, Identifiable {
let id = UUID()
let total: Double
let percentOfTotal: Double
let category: Category?
var description: String {
"\(name) \(percentOfTotal.noDecimalString)%"
}
var name: String {
category?.name ?? "Unknown"
}
static func < (lhs: TopTransaction, rhs: TopTransaction) -> Bool {
return lhs.total > rhs.total
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(name)
hasher.combine(total)
hasher.combine(percentOfTotal)
}
}




indexespecially with an unrelated array there is no way to tell SwiftUI there is a change prepare your data before you get to theForEach