To make a List selectable, the binding must be to the id of the items, in your case UUID. So, you would need @State private var selectedItem: UUID?
In MacOS, there's no Selection marker (as there is in iOS), so clicking on a row in a selectable list in MacOS highlights the row. At that point the ID of the row (Item) is in selectedItem as the UUID. To do anything further with the selected Item (row) you would need to retrieve it from the sourceList by filtering on the selected UUID.
I normally create a sequential Integer ID, starting from 0, when setting up the source data for a list so that I can use that as an index to the source data, provided I don't ever delete any item(s) - otherwise I would have to filter on the integer ID.
I also usually use a singleton, class based, data model that is an Observable Object with Published vars and perform all data processing in that model, with changes reflected in the SwiftUI views by a binding to the shared Data Model. For your example the SwiftUI View would be:
*** In my example, the user can select an Item without searching, just by clicking on a row.
struct ContentView: View {
@ObservedObject var dataModel = DataModel.shared
var body: some View {
VStack() {
TextField("Filter", text: $dataModel.searchString)
Spacer()
List(dataModel.filteredList, selection: $dataModel.selectedEntry) { entry in
HStack{
Text(entry.code)
Text(entry.name)
Text(entry.other)
}
}
Text("Selected Item is " + String(dataModel.selectedEntry ?? -1)). // negative means no current selection
}
}
}
The Data Model would be:
struct RegistryEntry: Identifiable, Hashable {
var id = 0
var code = ""
var name = ""
var other = ""
}
class DataModel : ObservableObject {
static let shared = DataModel()
var sourceList = [RegistryEntry]()
@Published var searchString = "" {
didSet {
if searchString == "" {
filteredList = sourceList
return
}
filteredList = sourceList.filter { $0.name.localizedCaseInsensitiveContains(searchString) }
}
}
@Published var selectedEntry : Int?
@Published var filteredList = [RegistryEntry]()
init() {
// set up sourceList by hardcoding or importing
// then set initial filtered list to source list
filteredList = sourceList
}
}
Regards, Michaela