I'm trying to make a ForEach loop that finds the index of the currently selected picker value. But I keep getting these error messages:
Referencing initializer 'init(_:id:content:)' on 'ForEach' requires that 'Text' conform to 'TableRowContent'
,
Static method 'buildBlock' requires that 'Text' conform to 'TableRowContent'
,
Closure containing control flow statement cannot be used with result builder 'TableRowBuilder'
@State private var loc: Double = 0
@State private var selectedLine = "N Q R W"
Picker("Lines", selection: $selectedLine) {
ForEach(station.groups, id: \.self) {
Text($0)
}
}
.padding(.all, 6.0)
.pickerStyle(.segmented)
ForEach (0 ..< station.groups.count, id: \.self) { i in //first 2 errors here
Text("Value: \(station.groups[i])")
if station.groups[i] == selectedLine { //second error
loc = station.groups.index(of: selectedLine)
}
}
station.group
is non-static variable from a JSON file. An example is ["N Q R W","one two three"]
or ["A C E","B D F M"]
Many thanks in advance.
Edit: I found a work around.
Picker("Lines", selection: $selectedLine) {
ForEach(0..<station.groups.count, id: \.self) { i in
Text(station.groups[i])
}
}
.padding(.all, 6.0)
.pickerStyle(.segmented)
selectedLine
is an Int
, now it outputs 0, 1, 2, & 3 instead of the array values.
CodePudding user response:
ForEach
is a View
it isn't a for loop and you can't use \.self
or use array.count
, you have to supply a key that is a unique identifier for the data, or make your data struct implement Identifiable
and have a let id
set it from the JSON data.