Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2.0 Sorting Array of Objects by Property

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. 
like image 718
felix_xiao Avatar asked Jul 30 '15 16:07

felix_xiao


People also ask

How do I sort an array in Swift?

To sort the array we use the sort() function. This function is used to sort the elements of the array in a specified order either in ascending order or in descending order. It uses the “>” operator to sort the array in descending order and the “<” operator to sort the array in ascending order.

How do you sort a struct array in Swift?

You can use . sorted() on it, Swift knows how to sort it. Let's say you have a struct of Book. And array with few books. You want to sort them alphabetically by title.


2 Answers

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.

like image 79
Rob Avatar answered Oct 20 '22 18:10

Rob


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

like image 33
Hanny Avatar answered Oct 20 '22 19:10

Hanny