Confused about the SelectionValue parameter in Lists vs CoreData
I have some working SwiftUI code that displays and can select the result of a fetch.
My code is essentially (edited to remove some not important flourishes)
@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")
}
}
}
So here the selection is controlled by an optional managed object.id parameter. I downloaded the Apple Sample migrating to SwiftData ("SampleTrips") and in the CoreData version of the app, they are essentially doing:
@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)
}
}
}
In this version, the selection is controlled by an optional managed object itself. I don't know why this works. Anyone have any ideas? Is that new in iOS 17?
Posted Aug 31, 2023, 10:48 PM UTC
The SampleTrips project is here: https://developer.apple.com/documentation/coredata/adopting\_swiftdata\_for\_a\_core\_data\_app