Sort array of custom objects by date swift
NSDate
can't be compared with <
directly. You can use NSDate
's compare
method, like in the following code:
meetingsData.sort({ $0.meetingDate.compare($1.meetingDate) == .OrderedAscending })
In the above code you can change the order of the sort using the NSComparisonResult
enum, that in Swift is implemented like the following:
enum NSComparisonResult : Int {
case OrderedAscending
case OrderedSame
case OrderedDescending
}
I hope this help you.
For Swift 3
meetingsData.sort(by: { $0.meetingDate.compare($1.meetingDate) == .orderedAscending})
OR
As dates are now directly comparable in Swift 3, For example.
let firstDate = Date()
let secondDate = Date()
if firstDate < secondDate {
} else if firstDate == secondDate {
} else if firstDate > secondDate {
}