Joakim Joakim - 1 year ago 74
Swift Question

Using SortInPlace with some optional values(nil)


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?

$0.0.shedueledTime!.compare(($0.1.shedueledTime)!) == NSComparisonResult.OrderedAscending



Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download