Note: If the Xcode canvas doesn't show anything in Live Preview, try an actual Simulator - no idea why canvas wasn't working in this demo but not important to the main issue.
I have a view with several pickers. Rather than flooding the namespace, I used an array storing the values. This works fine.
To improve it, I decided it would be more maintainable to use a dictionary, however, after making the switch, although there are no compile or runtime errors, it appears the picker's selection parameter isn't able to read or write to the dictionary?
struct ContentView: View {
@State private var data = [ // <- doesn't appear to be used by picker 1
"key1": 0,
"key2": 5
]
@State private var indices = [Int](repeating: 0, count: 2) // <- updates fine
var body: some View {
NavigationView {
Form {
// Picker 1, doesn't work
Picker(selection: $data["key1"], label: Text("dict")) {
ForEach(0..<100) {
Text(String($0)) // <- shows no value
}
}
// Picker 2, works fine
Picker(selection: $indices[0], label: Text("array")) {
ForEach(0..<100) {
Text(String($0))
}
}
}
}
}
}
That's visibly a known issue:
https://stackoverflow.com/questions/60853197/binding-swiftui-picker-to-value-held-in-dictionary
For some reason, dictionaries does not seem suited to hold a picker selection…
Found this other SO, where they define a new binding. Is it a hint to a solution ?