3

Behold two Pickers. The first, when uncommented (and the second commented) did not work -- when I change the room, the Text() does not get updated. But the code as shown here, with the second Picker, does.

The only difference is in the content closure. Why should how I create the content affect the binding? Is this a bug or expected behavior?

struct ContentView: View {
var rooms = ["Kitchen", "Dining Room", "Living Room", "Bathroom"]

@State private var selectedRoomIndex = 0

var body: some View {
    VStack {
        /* Doesn't work :-(
        Picker(selection: $selectedRoomIndex, label: Text("Room: ")) {
          ForEach(rooms, id: \.self){ room in
              Text(room)
        
          }
        }
        */

        /* This works, huzzah! But why? */
        Picker(selection: $selectedRoomIndex, label: Text("Room: ")) {
            ForEach(0 ..< rooms.count){
                Text(rooms[$0])
                
            }
        }
        
        Text("Chosen room: \(rooms[selectedRoomIndex])")
        Spacer()
    }
}

}

Michael Rogers
  • 1,318
  • 9
  • 22

1 Answers1

1

The Picker selection and content ForEach data must be the same type, that's why second variant work - selection is Int and ForEach element is Int, so to may first variant work it should be like below

Tested with Xcode 12 / iOS 14

@State private var selectedRoom: String = "Kitchen"

var body: some View {
    VStack {
        Picker(selection: $selectedRoom, label: Text("Room: ")) {
            ForEach(rooms, id: \.self){ room in
                Text(room)

            }
        }

        Text("Chosen room: \(selectedRoom)")
        Spacer()
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690