Search code examples
macosswiftuiswiftui-list

SwiftUI List with selector: selecting does not work for custom type (macOS)


I cannot figure out what I am doing wrong here; basically I fail to get a selection in a list of a custom type in my macOS app. Is there a conformance I am missing?

List1 represents a list of my custom type, in which I cannot select an entry, whereas in List2, where I am just using Int, it works.

enter image description here

These are my views:

struct ContentView: View {
    var body: some View {
        VStack {
            ListView1()
            Divider()
            ListView2()
        }
    }
}

struct ListView1: View {
    @State private var selection: Item? = nil
    
    var localSyslogEntries = [
        Item(message: "message 1"),
        Item(message: "message 2"),
        Item(message: "message 3"),
    ]
    
    var body: some View {
        List(localSyslogEntries, selection: $selection) { entry in
            VStack {
                Text(entry.id.uuidString)
                Divider()
            }
        }
        .frame(minHeight: 200.0)
    }
}

struct ListView2: View {
    @State private var selection: Int? = nil

    var body: some View {
        List(0..<10, id: \.self, selection: $selection) { index in
            VStack {
                Text("Index \(index)")
                Divider()
            }
        }
        .frame(minHeight: 200.0)
    }
}

And here's the custom type:

struct Item: Identifiable, Hashable {
    let id: UUID
    let message: String
    
    init(id: UUID = UUID(), message: String) {
        self.id = id
        self.message = message
    }
}

Solution

  • Add id

    List(localSyslogEntries, id: \.self, selection: $selection) { entry in