I have a class that includes an "updated order" property, and an array containing instances of that class. I want that array to be sorted based on the updated order of each of its elements. How can I do that?
Asked
Active
Viewed 60 times
-2
-
Do you mean "the objects in my array have a date property that marks when they were last updated; I want the array to be sorted by that date"? – TwoStraws Dec 18 '15 at 09:15
-
May be you are looking something similar to [this](http://stackoverflow.com/a/31729654/2955078) – Akhilrajtr Dec 18 '15 at 09:21
1 Answers
0
Following OP's clarification of what they want, they have a class or struct similar to this:
struct CustomObj {
var title: String
var date: NSDate
}
…and they looking to sort an array of such instances based on the date
property. Here's how it's done:
array.sortInPlace { (obj1, obj2) -> Bool in
return obj1.date.compare(obj2.date) == NSComparisonResult.OrderedAscending
}
You can test that it works using some example data:
array.append(CustomObj(title: "Testing 1", date: NSDate(timeIntervalSinceNow: 5000)))
array.append(CustomObj(title: "Testing 2", date: NSDate(timeIntervalSinceNow: 2000)))
array.append(CustomObj(title: "Testing 3", date: NSDate(timeIntervalSinceNow: 4000)))
array.append(CustomObj(title: "Testing 4", date: NSDate(timeIntervalSinceNow: 3000)))
array.append(CustomObj(title: "Testing 5", date: NSDate(timeIntervalSinceNow: 1000)))
print(array)
That will order the items 5, 2, 4, 3, 1.

TwoStraws
- 12,862
- 3
- 57
- 71