Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting nil Dates to the end of an Array

Trying to sort an array in Swift in descending order. This works well

objectArray.sort{ $0.date!.compare($1.date!) == .orderedDescending}

As you can see, I'm force unwrapping the date. I'm looking for another way so that if the date is nil, the object moves to the end of array.

like image 442
CalZone Avatar asked May 23 '17 20:05

CalZone


1 Answers

Maybe not the cleanest solution, but you can do it in one step with nil-coalescing.

objectArray.sort{ ($0.date ?? .distantPast) > ($1.date ?? .distantPast) }
like image 148
John Montgomery Avatar answered Oct 07 '22 12:10

John Montgomery