Joakim Joakim - 2 months ago 26
Swift Question

Using SortInPlace with some optional values(nil)

Hi

I have a dictionary with structs that I'll need to sort based on a time value(NSDate).

Most of the structs won't have that time value in them so their time-value(NSDate?) will be nil(optional).

The function I tried will crash when it tries a nil value.
How can I make this function sort the values and not crash when it tries to compare a nil?

AllBooks.SharedInstanse.browseBooks.sortInPlace(
{(
$0.0.shedueledTime!.compare(($0.1.shedueledTime)!) == NSComparisonResult.OrderedAscending

)
})


Thanks

Answer

It depends on what you want done with the nil values?

This will put them all at the start:

let today = Date()
let a: [Date?] = [nil, today.addingTimeInterval(24*60*60), nil, today]


let b = a.sorted(by: { ($0 ?? Date(timeIntervalSince1970: 0)) < ($1 ?? Date(timeIntervalSince1970: 0))})

Put that into a playground and you can play with it. To eliminate the nil values, use flatmap before you sort.

Comments