0

I have an array like this:

selectedMarks : [StatDetails] = [
  StatDetails(dateRanges: [2015-05-29 09:30:00 +0000, 2015-05-29 10:30:00 +0000], hours: 1),
  StatDetails(dateRanges: [2015-06-16 08:00:00 +0000, 2015-06-16 09:00:00 +0000], hours: 1),
  StatDetails(dateRanges: [2015-06-10 15:00:00 +0000, 2015-06-10 16:00:00 +0000], hours: 1)]

As you can see, selectedMarks is an array of "StatDetails" that contains 2 parameters:

1: dateRanges": an array of NSDate

2: hours: an Integer

I'm trying to figure out how to sort this array of StatDetails by the first element of the dateRanges array.

I tried with this but no success:

selectedMarks.sortInPlace({ $0.dateRanges < $1.dateRanges })

Any help with that??

jscs
  • 63,694
  • 13
  • 151
  • 195
Ruben
  • 1,789
  • 2
  • 17
  • 26
  • if you want to sort by the first element in your array of date ranges, you'll need to give it an index like so: `{ $0.dateRange[0] < $1.dateRanges[0] }` – fqdn Jun 29 '15 at 18:59
  • @fqdn I tried that before but I get a compilation error `Cannot invoke 'sort' with an argument list of type '((_, _) -> _)'` – Ruben Jun 29 '15 at 19:03
  • Possible duplicate of http://stackoverflow.com/questions/26577496/how-do-i-sort-a-swift-array-containing-instances-of-nsmanagedobject-subclass-by: You have to compare the dates with `compare()` or implement the `Comparable` protocol for NSDate. – Martin R Jun 29 '15 at 19:06

2 Answers2

2

This is how I made it, thanks of your help!

selectedMarks.sortInPlace({ $0.dateRanges[0].compare($1.dateRanges[0]) == NSComparisonResult.OrderedAscending })
Ruben
  • 1,789
  • 2
  • 17
  • 26
1

I was able to sort to write as below.

selectedMarks.sortInPlace{ $0.dateRanges.timeIntervalSince1970 < $1.dateRanges.timeIntervalSince1970 }
yuki0n0
  • 11
  • 1