The reason why the linked solutions did not work is because the array of tuples defined in the question contains optional types.
Checking for the optionals fixes the problem, without having to add new operators to NSDate.
An example, with 3 dates, and optional types:
var myArray: [(item1: String?, item2: NSDate?)] = []
myArray = [("now", NSDate()), ("now+30s", NSDate().dateByAddingTimeInterval(NSTimeInterval(30))), ("now-30s", NSDate().dateByAddingTimeInterval(NSTimeInterval(-30)))]
myArray.sortInPlace { (lhs, rhs) -> Bool in
if lhs.item2 != nil && rhs.item2 != nil {
return lhs.item2!.compare(rhs.item2!) == .OrderedAscending
}
return false // Return true if you want nil values first
}
Same code, if the types didn't allow for optionals:
var myArray: [(item1: String, item2: NSDate)] = []
myArray = [("now", NSDate()), ("now+30s", NSDate().dateByAddingTimeInterval(NSTimeInterval(30))), ("now-30s", NSDate().dateByAddingTimeInterval(NSTimeInterval(-30)))]
myArray.sortInPlace { (lhs, rhs) -> Bool in
return lhs.item2.compare(rhs.item2) == .OrderedAscending
}
MirekE's solution also works well, but you do not have control on where the nil values would end (they will be at the beginning).