Today I’ve been working on sorting tasks, as I’m using swiftUI and CoreData I use a FetchRequest with the following SortDescriptor:
NSSortDescriptor(keyPath: \Task.targetDate, ascending: true)
The idea being it will sort based on the task due date from smallest to the largest, meaning you’ll see the ones you should act on first at the top.
Great right?
Well… Although the sorting works as intended, if you have tasks that have a nil due date they will appear at the top. And, because we’re using the SwiftUI fetch request there’s no easy way to subclass it.
The easiest way around it, combine it with a sorted by within the List, in the View body. Here’s the implementation:
var body: some View {
List(tasks.sorted(by: { ($0 as Task).targetDate ?? Date(timeIntervalSinceNow: 9999999999999) < ($1 as Task).targetDate ?? Date(timeIntervalSinceNow: 9999999999999) }), selection: $selectedTask){ task in
And voila, now appears as intended:
Hope it helps, if you find a better solution by all means let me know at @MarcMasVi
Marc