How do I sort a swift array containing instances of NSManagedObject subclass by an attribute value (date)
Solution 1:
This is partly an issue with the Swift compiler not giving you a helpful error. The real issue is that NSDate
can't be compared with <
directly. Instead, you can use NSDate
's compare
method, like so:
days.sort({ $0.date.compare($1.date) == NSComparisonResult.OrderedAscending })
Alternatively, you could extend NSDate
to implement the Comparable
protocol so that it can be compared with <
(and <=
, >
, >=
, ==
):
public func <(a: NSDate, b: NSDate) -> Bool {
return a.compare(b) == NSComparisonResult.OrderedAscending
}
public func ==(a: NSDate, b: NSDate) -> Bool {
return a.compare(b) == NSComparisonResult.OrderedSame
}
extension NSDate: Comparable { }
Note: You only need to implement <
and ==
and shown above, then rest of the operators <=
, >
, etc. will be provided by the standard library.
With that in place, your original sort function should work just fine:
days.sort({ $0.date < $1.date })
Solution 2:
In Swift 3, dates are now directly comparable:
let aDate = Date()
let bDate = Date()
if aDate < bDate {
print("ok")
}
Old swift: An alternative would be to sort on the timeIntervalSince1970 property of the date object, which is directly comparable.
days.sort({$0.date.timeIntervalSince1970 < $1.date.timeIntervalSince1970})
Solution 3:
In swift2.1
use this lines of code
array.sortInPlace({ $0.date.compare($1.date) == NSComparisonResult.OrderedAscending })
Solution 4:
Update__ Swift 4,
let sortedData = dataToSort.sorted(by: { (obj1, obj2) -> Bool in
return obj1.date < obj2. date
})