11

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?

3
  • Date doesn't have a time property. Where does this come from? Commented Sep 20, 2016 at 23:48
  • @TomHarrington - I think time is the name of a Date property of his alarm type. Commented Sep 21, 2016 at 0:00
  • self.messages.sort(by: { $0.date.compare($1.date) == .orderedAscending }) Works for me. Commented Jul 20, 2017 at 12:19

1 Answer 1

20

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I think they do have different dates! And thanks for that rob, I'll try that and let you know how it turns out.
I'm getting errors with the Calendar.startOfDay part, this is the error that I'm getting Use of instance member 'startOfDay' on type 'Calendar'; did you mean to use a value of type 'Calendar' instead?
thanks worked perfect sameTitleArr.sort { $0.startDate > $1.startDate } for descending

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.