Sort an array of optional items that holds yet another optional

后端 未结 2 1244
后悔当初
后悔当初 2020-12-11 06:48

How can I sort an array of optionals that holds an optional NSdate?

class HistoryItem {
   var dateCompleted: NSDate?
}

let firstListObject = someListOfObje         


        
相关标签:
2条回答
  • 2020-12-11 07:05

    Your sort function could use a combination of optional chaining and the nil 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 t1.compare(t2) == NSComparisonResult.OrderedAscending
    }
    

    This would sort the items on the dateCompleted value, and all items that are nil and items with dateCompleted == nil are treated as "in the distant past" so that they are ordered before all other items.


    Update for Swift 3 (assuming that dateCompleted is a Date):

    array.sort { (item1, item2) -> Bool in
        let t1 = item1?.dateCompleted ?? Date.distantPast
        let t2 = item2?.dateCompleted ?? Date.distantPast
        return t1 < t2
    }
    
    0 讨论(0)
  • 2020-12-11 07:10

    Swift 4. if you want to keep optional values at the end, for example, use Int.max:

    self.values.sort { (item1, item2) -> Bool in
        let value1 = item1.seconds ?? Int.max
        let value2 = item2.seconds ?? Int.max
        return value1 < value2
    }
    
    0 讨论(0)
提交回复
热议问题