Reputation: 21
I'm trying to convert to an Array and sort some dates from a coreData Entity called Historic, it's working but I'm using forced unwrap to sort the array
private var sortedHistoric: [Historic] {
var aux = Array(medication.dates as? Set<Historic> ?? [])
aux = aux.sorted(by: { $0.dates!.timeIntervalSinceNow > $1.dates!.timeIntervalSinceNow })
return aux
}
Is there a way to try to sort the array and if there is an error just ignore it and just leave unsorted, so I don't have to use force unwrap?
Upvotes: 0
Views: 59
Reputation: 131491
As jnpdx says, you need to decide what you want to do when the Date field is nil. If treating nil dates as midnight Jan 1, 2001 is ok, you could rewrite your sort like this:
let nilDateValue = 0
aux = aux.sorted(by: { $0.dates.timeIntervalSinceReferenceDate ?? nilDateValue > $1.dates.timeIntervalSinceReferenceDate ?? nilDateValue })
(That would cause all the nil dates in your aux array to sort before any date since Jan 1, 2001.)
You can use a different, large value (like 252423993599, a date on 31 January in the year 9999) for nilDateValue
if you want nil dates to sort to the ned of the list.
Upvotes: 0