对包含另一个可选项的可选项数组进行排序

时间:2014-10-04 09:22:08

标签: arrays sorting swift

如何对包含可选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]

如何根据dateCompleted对数组进行排序?

2 个答案:

答案 0 :(得分:16)

您的排序功能可以使用可选链接和零的组合 合并算子:

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

这会对dateCompleted值上的项目以及所有项目进行排序 是nildateCompleted == nil的项目被视为“在遥远的过去” 这样他们就可以在所有其他物品之前订购。


更新 Swift 3 (假设dateCompletedDate):

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

答案 1 :(得分:1)

Swift 4.如果要在末尾保留可选值,例如,请使用Int.max:

self.values.sort { (item1, item2) -> Bool in
    let value1 = item1.seconds ?? Int.max
    let value2 = item2.seconds ?? Int.max
    return value1 < value2
}