My code to show a list from a fetch that can be selected is (simplified) as follows
@FetchRequest(sortDescriptors: []) private var players: FetchedResults<PlayerEntity>
@State private var selectedPlayerID : PlayerEntity.ID?
var body: some View {
NavigationSplitView {
List(players, selection: $selectedPlayerID) { player in
Text(player.shortName ?? "")
}
.navigationTitle("Players")
} detail: {
if let id = selectedPlayerID, let player = players.first(where: {$0.id == id}) {
Text("Do Something")
}
}
}
I'm using the state variable of type ID PlayerEntity.ID?
to hold the selection.
However, I noticed the sample app from migrating to SwiftData ("SampleTrips") is essentially doing it like this:
@FetchRequest(sortDescriptors: [SortDescriptor(\.startDate)])
private var trips: FetchedResults<Trip>
@State private var showAddTrip = false
@State private var selection: Trip?
@State private var path: [Trip] = []
var body: some View {
NavigationSplitView {
List(selection: $selection) {
ForEach(trips) { trip in
TripListItem(trip: trip)
//... removed some extra code
}
}
//... removed some extra code
.navigationTitle("Upcoming Trips")
//... removed some extra code
} detail: {
if let selection = selection {
NavigationStack {
TripDetailView(trip: selection)
}
}
}
The sample code is able to pass an optional managed object type Trip?
to hold the selection rather than the ID type. When I try to replicate that behavior, I can't. Does anyone know what would be different?