Generic parameter 'SelectionValue' could not be inferred

Hi! What is wrong with this code and why does this work for a Picker but not a List?

Code Block language
struct ContentView: View {
    enum FooBar: CaseIterable, Identifiable {
        public var id : String { UUID().uuidString }
       
        case foo
        case bar
        case buzz
        case bizz
    }
    @State var selectedFooBar: FooBar = .bar
    var body: some View {
        VStack {
            Picker("Select", selection: $selectedFooBar) {
                ForEach(FooBar.allCases) { item in
                    Text(self.string(from: item)).tag(item)
                }
            }
           
            List(FooBar.allCases, selection: $selectedFooBar) { item in
                Text(self.string(from: item)).tag(item)
            }
           
            Text("You selected: \(self.string(from: selectedFooBar))")
        }
    }
    private func string(from item: FooBar) -> String {
        var str = ""
        
        switch item {
        case .foo:
            str = "Foo"
            
        case .bar:
            str = "Bar"
            
        case .buzz:
            str = "Buzz"
            
        case .bizz:
            str = "Bizz"
        }
        return str
    }
}


In this case, the initializer you are using has this method signature:

Code Block swift
List<Data, RowContent>(_ data: Data, selection: Binding<SelectionValue?>?, rowContent: @escaping (Data.Element) -> RowContent) where Content == ForEach<Data, Data.Element.ID, HStack<RowContent>>, Data : RandomAccessCollection, RowContent : View, Data.Element : Identifiable


And the glitch you're experiencing comes from the type selection expects. You're binding it to the state of selectedFooBar, which is of type FooBar (Binding<FooBar>), but it actually takes a binding of an optional value (Binding<FooBar?>). So if you change line 13 to read @State var selectedFooBar: FooBar? = .bar, you should be back on track!
@natlaw -

I tried this approach, setting the initial value of the @State - When I tap on a row, this value doesn't update. Do you have any thoughts on that?
@State var selectedFooBar: FooBar? = .bar

selection binding type should be nullable

Generic parameter 'SelectionValue' could not be inferred
 
 
Q