我正在嘗試創建一個 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($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是來自 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 而不是陣列值。
uj5u.com熱心網友回復:
ForEach是一個View它不是一個 for 回圈,你不能使用\.self或使用array.count,你必須提供一個作為資料唯一識別符號的鍵,或者讓你的資料結構實作Identifiable并let id從 JSON 資料中設定它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/454398.html
