Sort own class in swift on date property

Swift arrays can be easily sorted with the function sort(<#isOrderedBefore: (T, T) -> Bool##(T, T) -> Bool#>). You can use closures or move it to a separate function. I prefer to move all code to a separate function as I use the sorting multiple times in my project.

In my example I sort a class called Transaction which contains a field lastUpdated of type NSDate. My function has to return a boolean to determine whether the first element has to be placed before the next one or after it. The function compare returns a NSComparisonResult which I then can check for .OrderedDescending to see if it's later then the first date.

func sortTransactionsDESC(compare:Transaction, to:Transaction) -> Bool {
    return compare.lastUpdated.compare(to.lastUpdated) == NSComparisonResult.OrderedDescending
}

To use it on the array transactions, simply call sort with the new sort function:

transactions.sort(self.sortTransactionsDESC)

self has to be used here