Sorting an array of optional elements that contains another option

How can I sort the options array that contains an optional NSdate?

class HistoryItem {
   var dateCompleted: NSDate?

let firstListObject = someListOfObject.last
let secondListObject = someOtherListOfObject.last
let thirdListObject = evenSomeOtherListOfObject.last //Last returns 'T?'

var array = [firstListObject , secondListObject, thirdListObject]


How can I sort the array based on dateCompleted?


source to share

1 answer

Your sort function can use a combination of the optional chaining and the null coalescing operator:

sort(&array) {
    (item1, item2) -> Bool in
    let t1 = item1?.dateCompleted ?? NSDate.distantPast() as! NSDate
    let t2 = item2?.dateCompleted ?? NSDate.distantPast() as! NSDate
    return == NSComparisonResult.OrderedAscending


This sorts the items in value dateCompleted

and all items that are nil

, and items with are dateCompleted == nil

considered "in the distant past" so that they are ordered before all other items.

Update for Swift 3 (assuming that dateCompleted

is Date


array.sort { (item1, item2) -> Bool in
    let t1 = item1?.dateCompleted ?? Date.distantPast
    let t2 = item2?.dateCompleted ?? Date.distantPast
    return t1 < t2




All Articles