如何排序包含可选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对数组排序?

最佳答案

您的排序功能可以结合使用可选链接和nil
合并运算符:

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值上的项目以及所有
nil,带有dateCompleted == 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
}

关于arrays - 对可选项目数组进行排序,该数组包含另一个可选项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31035346/

10-11 08:13