Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Swift 3) Trying to sort an array of class objects by Date in swift 3?

Tags:

ios

swift3

I have an array of objects that has a member that is type Date, and I'm trying to sort the whole array by Date, and it's not sorting correctly. This is the code I'm using, the name of the array is alarms and the name of the member type Date is time.

alarms.sort(by: { $0.time.compare($1.time) == .orderedAscending })

and whenever I sort it it just doesn't work correctly, and I'm testing it by printing all the values in a for loop.

Can someone help me with the syntax for this?

like image 713
Jolaroux Avatar asked Sep 20 '16 23:09

Jolaroux


1 Answers

The compare is a NSDate function. With Date you can just use < operator. For example:

alarms.sort { $0.time < $1.time }

Having said that, compare should work, too, though. I suspect there's some deeper issue here, that perhaps your time values have different dates. You might only be looking at the time portion, but when comparing Date objects, it considers both the date and time. If you only want to look at the time portion, there are several ways of doing that, for example, look at the time interval between time and the start of the day:

let calendar = Calendar.current

alarms.sort {
    let elapsed0 = $0.time.timeIntervalSince(calendar.startOfDay(for: $0.time))
    let elapsed1 = $1.time.timeIntervalSince(calendar.startOfDay(for: $1.time))
    return elapsed0 < elapsed1
}

There are lots of ways to do this, but hopefully this illustrates the idea.

like image 178
Rob Avatar answered Nov 15 '22 22:11

Rob