Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

sorting - Sort an array of optional items that holds yet another optional

How can I sort an array of optionals that holds 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 array based on dateCompleted?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...