How to make binding work properly

How do I make my @State value change when the picker changes?

Code Block
struct ContentView: View {
@State var Choioce: Int?
var settings = ["ch1", "ch2", "ch3"]
var body: some View {
Picker("Options", selection: $Choioce) {
Text("Please Select One")
ForEach(0 ..< settings.count) { index in
Text(self.settings[index])
.tag(index)
}
}
Text("You selected: \(settings[Choioce!])")
}
}

The You selected text view never changes.

The You selected text view never changes.

Your code does not compile in Xcode 11.6 nor in Xcode 12 beta 5.
With a little modification, the modified code compiles but causes Fatal error: Unexpectedly found nil while unwrapping an Optional value.
Code Block
var body: some View {
VStack {
Picker("Options", selection: $Choioce) {
Text("Please Select One")
ForEach(0 ..< settings.count) { index in
Text(self.settings[index])
.tag(index)
}
}
Text("You selected: \(settings[Choioce!])")
}
}


Please show the exact code which can reproduce your issue. When something weird is going on, a slight change will change the behavior.
I had this in a VStack I just missed it when I was posting. I figured it out. Add a tag to the text view inside the picker that says please select one and set it to Optional<Int>.none. This should solve the problem of the You Selected text view.
When implementing a view which supports a selection binding, the binding's type must match the identifiable element of the displayed data. For example, you could do either of the following to achieve your desired behavior—

Transform the index of the ForEach to Int? for the tag view modifier:
Code Block swift
struct ContentViewA: View {
    @State private var selection: Int?
    var settings = ["ch1", "ch2", "ch3"]
    var body: some View {
        // ⚠️ The selection binding's wrapped value must match the identifiable type of the data element (e.g., Int?):
        Picker("Options", selection: $selection) {
            Text("Please Select One")
            ForEach(0 ..< settings.count) { index in
                Text(self.settings[index])
                    // ⚠️ The tag's value must match the identifiable type of the data element (e.g., Int?):
                    .tag(Optional(index))
            }
        }
        Text("You selected: \(selection != nil ? settings[selection!] : "")")
    }
}


Or, use the element type of the displayed data directly:
Code Block swift
struct ContentViewB: View {
    @State private var selection: String = ""
    var settings = ["ch1", "ch2", "ch3"]
    var body: some View {
        // ⚠️ The selection binding's wrapped value must match the identifiable type of the data element (e.g., String):
        Picker("Options", selection: $selection) {
            Text("Please Select One")
            ForEach(settings, id: \.self) { setting in
                Text(setting)
            }
        }
        Text("You selected: \(selection)")
    }
}

How to make binding work properly
 
 
Q