2

The follow code compiles and runs, but only the pickers bound to values in the array work. Those held in a dictionary fail. Any ideas why this maybe the case?

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])
                }
            }
        }
    }
}
Philip Pegden
  • 1,732
  • 1
  • 14
  • 33

1 Answers1

0

Could the answer be something because of this?

In short you can not use a ForEach because:

  • It watches a collection and monitors movements. Impossible with an unordered dictionary.
  • In each case above the ```ForEach``` iterates over the array ```options```. So I'm not sure that this is the reason. The issue here is where the choice is stored. – Philip Pegden Feb 04 '21 at 21:20