SwiftUI: Picker doesn't update text in same view

Viewed 280

I have this simple situation:

struct User: Hashable, Identifiable {
    var id: Int
    var name: String
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
}

let bob = User(id: 1, name: "Bob")
let john = User(id: 2, name: "John")
let users = [bob, john]

struct ParentView: View {    
    @State private var user: User?

    var body: some View {
        VStack(spacing: 0) {
            // Other elements in view...
            Divider()
            ChildPickerView(user: $user)
            Spacer()
        }
    }    
}

struct ChildPickerView: View {
    @Binding var user: User?
    
    var body: some View {
        HStack {
            Text("Selected : \(author?.name ?? "--")")
            Picker(selection: $user, label: Text("Select a user")) {
                ForEach(0..<users.count) {
                    Text(users[$0].name)
                }
            }
        }
        .padding()
    }
}

When I select another value in the picker, the name in the Text() above isn't updated. However, when tapping the picker again, there is a tick near the selected user, which means the value has actually been selected. Why is the text not updated then?

Thank you for your help

1 Answers

Type of selection and picker content id or tag should be the same. Find below fixed variant.

Tested with Xcode 12.1 / iOS 14.1.

    VStack {
        Text("Selected : \(user?.name ?? "--")")
        Picker(selection: $user, label: Text("Select a user")) {
            ForEach(users) {
                Text($0.name).tag(Optional($0))
            }
        }
    }
Related