Using NSSortDescriptor to sort Dates and nil values

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.

Untitled Artwork

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:

Screen Shot 2021 09 11 at 1 56 48 PM

Hope it helps, if you find a better solution by all means let me know at @MarcMasVi

 

Marc