Search code examples
iosswiftswiftui

List selection doesn't work when selection is optional custom type


I have this simple example:

struct Message: Identifiable, Hashable {
    let id = UUID()
    let content: String
}

struct ContentView: View {
    @State private var selection: Message?
    @State private var messages: [Message] = [
        Message(content: "Hello"),
        Message(content: "World")
    ]

    var body: some View {
        NavigationStack {
            List(selection: $selection) {
                ForEach(messages) { message in
                    Text(message.content)
                        .tag(message as Message?)
                }
            }
            .navigationTitle("List")
           
        }.onChange(of: selection) { oldValue, newValue in
            print("Old value \(String(describing: oldValue))")
            print("New value \(String(describing: newValue))")
        }
    }
}

I am trying to select the appropriate model when an item in the list is selected. However, the selection in this example does not function as I expected.

If I change the selection to use UUID, the selection works. However, I need to grab a corresponding model object when an item in the list is selected.

What am I doing wrong?


Solution

  • try using .tag(message), works for me