I have an array containing an object called HistoryObject
and it has properties such as "date", "name", etc.
I am sorting the array like so:
let sortedArray = HistoryArray.sort({ $0.date.compare($1.date) == NSComparisonResult.OrderedDescending})
which is supposed to sort the date from newer to oldest. For example:
- Jun 30, 2016
- Jun 29, 2016
etc..
But when my array contains "Jul 2, 2016" the sorted array becomes:
- Jun 30, 2016
- Jun 29, 2016
- Jul 2, 2016
Where "Jul 2, 2016" should be on top after sorting, now it's on the bottom? How can I fix this problem?
For Swift 3
Using Swift 4 & Swift 3
Using Swift 2
For example you have the array with dates and another 1 array, where you will save the converted dates:
After that we convert the dates:
And the result:
You have an array
historyArray
that contains an array ofHistoryObject
. EachHistoryObject
contains a date string in the form "MM dd, yyyy"Edit:
(You want to sort your history objects by their date values. It is a bad idea to try to sort objects with date strings by those date strings, since you have to convert the date strings to Cocoa
Date
objects for every comparison, so you end up converting the dates to date objects over and over and over. In a benchmark I did, this causes the sort to run 1200X slower than if you batch-convert your date strings toDate
objects before sorting, as outlined below.)In order to do that efficiently you need to first get
Date
values for all of the objects. One way to do that would be to add a lazyDate
var to yourHistoryObject
that is calculated from the date string. If you don't want to do that you can:zip()
function to combine the array of history objects and the array of date objects into an array of tuples.The code to do that might look something like this:
Version 1
If you add a
lazy var date
to your HistoryObject the sorting code is a LOT simpler:Version 2:
Avoiding extra variable of convertedArray
Using Swift 4 & Swift 3