TL;DR
您的变量currencyCode 与ForEach 中每个元素的ID 类型不匹配。遍历您的 ForEach 中的代码,或者将您的 Picker 传递给索引。
以下是三个等效示例。请注意,传递给 Picker 的 @State 变量始终与 ForEach 迭代的元素的 ID 匹配:
另外请注意,我为@State 变量选择了一个不在数组中的默认值(“”、-1、UUID()),因此在加载表单时不会显示任何内容。如果您需要默认选项,只需将其设为 @State 变量的默认值即可。
示例 1:迭代代码(即字符串)
struct ContentView: View {
@State private var currencyCode: String = ""
var codes: [String] = ["EUR", "GBP", "USD"]
var body: some View {
NavigationView {
Form {
Section {
Picker(selection: $currencyCode, label: Text("Currency")) {
// ID is a String ----v
ForEach(codes, id: \.self) { (string: String) in
Text(string)
}
}
}
}
}
}
}
示例 2:迭代索引(即 Int)
struct ContentView: View {
@State private var selectedIndex: Int = -1
var codes: [String] = ["EUR", "GBP", "USD"]
var body: some View {
NavigationView {
Form {
Section {
Picker(selection: $selectedIndex, label: Text("Currency")) {
// ID is an Int --------------v
ForEach(codes.indices, id: \.self) { (index: Int) in
Text(self.codes[index])
}
}
}
}
}
}
}
示例 3:通过 ID 类型(即 UUID)迭代可识别的结构
struct Code: Identifiable {
var id = UUID()
var value: String
init(_ value: String) {
self.value = value
}
}
struct ContentView: View {
@State private var selectedUUID = UUID()
var codes = [Code("EUR"), Code("GBP"), Code("USD")]
var body: some View {
NavigationView {
Form {
Section {
Picker(selection: $selectedUUID, label: Text("Currency")) {
// ID is a UUID, because Code conforms to Identifiable
ForEach(self.codes) { (code: Code) in
Text(code.value)
}
}
}
}
}
}
}