I want to add a row number to a race list as shown above. Currently everyone is coming first. It's conditional as some people didn't finish (DNF).
So first I set up an ObservableObject:
class GlobalSettings: ObservableObject {
@Published var counter: Int = 0
}
The structure that display each row is called from:
Section {
List {
ForEach(entrants) { entrant in
ResultsCell(entrant: entrant)
}
}
}
The row is displayed by ResultsCell:
struct ResultsCell: View {
let entrant: EntrantsDatabase1
@EnvironmentObject var globalSettings: GlobalSettings
var body: some View {
HStack {
Spacer()
.frame(width: 5)
if entrant.dateTime != 999.999 {
globalSettings.counter += 1
Text("\(globalSettings.counter).")
// Text("1.")
.frame(width: 20, height: 40, alignment: .leading)
.bold()
} else {
Text("-")
.frame(width: 20, height: 40, alignment: .leading)
.bold()
}
Spacer()
.frame(width: 5)
CircledText(text: String(entrant.number))
.frame(width: 48, height: 40, alignment: .leading)
.bold()
Spacer()
.frame(width: 10)
Text(entrant.name)
.frame(width: 160, height: 40, alignment: .leading)
.bold()
Spacer()
.frame(width: 10)
if entrant.dateTime != 999.999 {
Text("\(entrant.dateTime, specifier: "%.3f")")
.frame(width: 70, height: 40, alignment: .trailing)
.bold()
} else {
Text("DNF")
.frame(width: 70, height: 40, alignment: .trailing)
.bold()
}
}
.listRowBackground(entrant.dateTime == 999.999 ? Color.red: Color(.tertiarySystemBackground))
}
}
The row counter only increments if the person finishes. Using this approach I get a
'buildExpression' is unavailable: this expression does not conform to 'View'
error when I try and use the globalSettings.counter variable.
Is this approach valid/Workable?

Section). Because at the timeListrenders, you already know how manydateTimethat!= 999.999.Viewyou cannot have "normal" procedural code likeglobalSettings.counter += 1. This type of code needs to be in special places (eg .onAppear{...}, Button action etc...) or in functions.Sectionyou get the same error, because as I said before, in SwiftUIViewyou cannot have "normal" procedural code like that in the body, only otherView. There are many SO posts on this subject, search for them.