Search code examples
swiftswiftuipicker

Picker inside of form no longer selecting


I have a picker inside of a form. Previously it was selecting the items correctly, however, after changing the code to fix another issue it no longer works. The items the picker is using is fetched from coredata. How can I fix this issue?

@FetchRequest(sortDescriptors: [])
var sources: FetchedResults<Source>
@State private var selectedSource = 0

Here is the code I am using for the picker.

Picker(selection: $selectedSource, label: Text("Source")) {
    ForEach(sources, id: \.self) { source in
        Text(source.name!)
            .tag(source)
    }
}

Here is a link to a video of the issue. Video


Solution

  • The type that you provide in Picker(selection:) (which is currently Int -- selectedSource) needs to be the same as the type that you provide in tag(), which is currently Source.

    You could, for example, use the ID of Source (I'm assuming it has one) as your selectedSource and then use the same IDs in your tag()