How do I reorder list item in Swift Data with the @Query request? I have a list pulling from Swift Data that I would like to make reorderable but it throws this error: "Cannot use mutating member on immutable value: 'locations' is a get-only property". Is it possible to reorder Swift Data items?
How to reorder list items with Swift Data?
Can you provide a minimum reproducible code so that others can help
Here is the code I have currently:
@Query private var locations: [Location]
ForEach(locations) { location in
LocationListRowView(location: location)
}
.onDelete(perform: { indexSet in
for index in indexSet {
context.delete(locations[index])
}
})
.onMove(perform: move)
func move(from source: IndexSet, to destination: Int) {
locations.move(fromOffsets: source, toOffset: destination)
}
The error comes up on the line in the move function.
I added a property called order to the types I want to move. here is my moveList method which is called when a user moves a list item in my app. There's still an issue when moving items down but it works for the most part.
private func moveList(from source: IndexSet, to destination: Int) {
guard
searchText.isEmpty,
filteredLists.lists.count > 1
else {
return
}
debugPrint("Source: \(source), destination: \(destination)")
let sourceList = getList(at: source)
debugPrint("Source List: \(sourceList.name) to position \(destination)")
let dropIndex = destination <= 0 ? 0 : destination < filteredLists.lists.count ? destination : destination - 1
debugPrint("dropIndex: \(dropIndex)")
let dropList = filteredLists.lists[dropIndex]
let isMovingUp = destination < sourceList.order
dropList.order = isMovingUp ? dropList.order + 1 : dropList.order - 1
debugPrint("Drop Location: \(dropList.name), position: \(dropList.order)")
sourceList.order = destination
debugPrint("Source List: \(sourceList.name) to position \(sourceList.order)")
reorderLists()
}