Sorting NSArray containing NSDate objects

穿精又带淫゛_ 提交于 2019-11-28 13:57:34

Using the native Array type in Swift. If you are interfacing with legacy code from ObjC, use this:

let array = unsortedArray.sortedArrayUsingSelector("compare:")

If you use Swift array.

let datesArray = [ NSDate(), NSDate(timeIntervalSinceNow: 60), NSDate(timeIntervalSinceNow: -60) ]
let sorter: (NSDate, NSDate) -> Bool = { $0.compare($1) == .OrderedAscending }
let sortedDatesArray = datesArray.sort(sorter)

You can make your NSDate conform to protocol Comparable and then you can just compare it the same way you do with number data type:

extension NSDate: Comparable {}

public func <(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.compare(rhs) == .OrderedAscending
}

var dates = [NSDate(),NSDate(timeIntervalSinceNow: -600)]   // ["Dec 28, 2015, 2:48 AM", "Dec 28, 2015, 2:38 AM"]
dates.sortInPlace(<)
dates // ["Dec 28, 2015, 2:38 AM", "Dec 28, 2015, 2:48 AM"]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!