SwiftUI List selection is not consistent across initializers.

When using an initializer like List(selection: $selection) the touch is never recognized as a selection, even if the data objects conform to Identifiable. It doesn't seem to matter much what kind of views each cell consists of.

As the title suggests, the touch is correctly recognized as a selection when an initializer like List(identifiableObjects, id: \.self, selection: $selection) is used.

It is also worth reporting that List(identifiableObjects, id: \.id, selection: $selection) does not perform the selection either.

This has been checked in Xcode 15 beta 5.

Hello,

I suspect that you are not tagging your RowContent views with the appropriate value (whose type matches the selection properties type), does the following work for you?

struct ContentView: View {
    
    @State private var selection: Item?
    
    @State private var items = [Item(), Item(), Item()]
    
    var body: some View {
        List(items, selection: $selection) { item in
            Text(item.id.uuidString).tag(item)
        }
    }
}

struct Item: Identifiable, Hashable {
    let id = UUID()
}
Accepted Answer

Hi @rjantz ,

The reason you are seeing this behavior may be caused by your selection variable type.

Say your list is made of a few items of type Item

struct Item: Identifiable, Hashable {
let id = UUID()
let name: String
}
struct ListExample: View {
    @State private var items: [Item] = [Item(name: "Item1"), Item(name: "Item2"]
    @State private var selection: Item.ID?
    
    var body: some View {
        NavigationStack{
            List(items, selection: $selection ){ item in
                        NavigationLink(item.name){
                          DetailView(item.name)
                }
        }

Here, my selection is of type Item.ID, and Item conforms to Identifiable and has an id, so I do not need to specify an ID in the List initializer.

You also can specify this with List(items, id: \.id, selection: $selection) and it will work the exact same. If you would like the id parameter in the List initializer to be of \.self, then try making your selection variable @State private var selection: Item? so that these two variable types match up.

Please try running this. If this does not work for you, please file a bug with http://feedbackassistant.apple.com and post the feedback number here.

SwiftUI List selection is not consistent across initializers.
 
 
Q