将SwiftUI选取器绑定到字典中的值



以下代码编译并运行,但只有绑定到数组中值的拾取器才能工作。字典里的那些不及格。你知道为什么会这样吗?

import SwiftUI
struct ContentView: View {
private var options : [String] = ["Bonjour", "Hello", "Hola"]
@State private var choicesHeldInArray = [0, 2]
@State private var choicesHeldInDict: [String: Int] = ["C3": 2, "C4":1]
var body: some View {
VStack {
Picker(selection: $choicesHeldInArray[0], label: Text("Choice 1")) {
ForEach(0 ..< options.count) {
Text(self.options[$0])
}
}
Picker(selection: $choicesHeldInArray[1], label: Text("Choice 2")) {
ForEach(0 ..< options.count) {
Text(self.options[$0])
}
}
Picker(selection: $choicesHeldInDict["C3"], label: Text("Choice 3")) {
ForEach(0 ..< options.count) {
Text(self.options[$0])
}
}
Picker(selection: $choicesHeldInDict["C4"], label: Text("Choice 4")) {
ForEach(0 ..< options.count) {
Text(self.options[$0])
}
}
}
}
}

答案可能是因为这个吗?

简而言之您不能使用ForEach,因为:

  • 它监视一个集合并监视移动。用无序的字典是不可能的

最新更新