39

In Swift 2.0, how would you go about sorting an array of custom objects by a property? I know in Swift 1.2, this was done using sorted() and sort(). However, these methods no longer work in Xcode 7 beta 4. Thanks!

For example:

class MyObject: NSObject {
    var myDate : NSDate
}

...

let myObject1 : MyObject = MyObject() //same thing for myObject2, myObject3

var myArray : [MyObject] = [myObject1, myObject2, myObject3] 

//now, I want to sort myArray by the myDate property of MyObject.
James Webster
  • 31,873
  • 11
  • 70
  • 114
felix_xiao
  • 1,608
  • 5
  • 21
  • 29

4 Answers4

76

In Swift 2:

  • You can use sort method, using compare to compare the two dates:

    let sortedArray = myArray.sort { $0.myDate.compare($1.myDate) == .OrderedAscending }  // use `sorted` in Swift 1.2
    
  • Or, if you want to sort the original array, you can sortInPlace:

    myArray.sortInPlace { $0.myDate.compare($1.myDate) == .OrderedAscending }  // use `sort` in Swift 1.2
    

In Swift 3:

  • to return a sorted rendition of the array, use sorted, not sort

    let sortedArray = myArray.sorted { $0.myDate < $1.myDate }
    
  • to sort in place, it's now just sort:

    myArray.sort { $0.myDate < $1.myDate }
    

And with Swift 3's Date type, you can use the < operator.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Example for Sorting Strings let myArray = ["Zen", "Step 12", "Apple"] let sortedArray = myArray.sort({ x, y in return x.localizedStandardCompare(y) == NSComparisonResult.OrderedAscending }) dump(sortedArray) – Abhijeet Sep 22 '15 at 03:18
  • The Swift 3 rendition works fine. I suspect there's something else wrong with your code. If you're still having problems, post your own, new question on Stack Overflow with [reproducible example of your problem](http://stackoverflow.com/help/mcve). – Rob Oct 22 '16 at 08:58
10

If you want to sort original array of custom objects. Here is another way to do so in Swift 2.1

var myCustomerArray = [Customer]()
myCustomerArray.sortInPlace {(customer1:Customer, customer2:Customer) -> Bool in
        customer1.id < customer2.id
    }

Where id is an Integer. You can use the same < operator for String as well.

You can learn more about its use by looking at an example here: Swift2: Nearby Customers

Hanny
  • 1,322
  • 15
  • 20
0

In swift 3.0

I have taken the assumption same as the example asked in the question.

i.e customObject is MyObject with variable myDate. The array of the MyObject is myArray.We can sort like this simply.

myArray.sort(by: { (one: MyObject, two: MyObject) -> Bool in
    one. myDate < two. myDate
})
jaiswal Rajan
  • 4,641
  • 1
  • 27
  • 16
-2

sort is now sortInPlace (or something similar) with the same parameters as sort.

gnasher729
  • 51,477
  • 5
  • 75
  • 98