ForEach & indexof SwiftUI 继续给予 "Closure containing control flow statement cannot be used with result builder 'TableRowBuilder'"

ForEach & indexof SwiftUI keep giving "Closure containing control flow statement cannot be used with result builder 'TableRowBuilder'"

我正在尝试创建一个 ForEach 循环来查找当前选定的选择器值的索引。但我不断收到这些错误消息: 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([=11=])
   }
}
.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 是来自 JSON 文件的非静态变量。例如 ["N Q R W","one two three"]["A C E","B D F M"] 非常感谢。

编辑:我找到了解决方法。

Picker("Lines", selection: $selectedLine) {
   ForEach(0..<station.groups.count, id: \.self) { i in
      Text(station.groups[i])
   }
}
.padding(.all, 6.0)
.pickerStyle(.segmented)

selectedLine 是一个 Int,现在它输出 0、1、2 和 3 而不是数组值。

ForEach 是一个 View 它不是 for 循环,你不能使用 \.self 或使用 array.count,你必须提供一个密钥是数据的唯一标识符,或者使您的数据结构实现 Identifiable 并从 JSON 数据中设置 let id