简体   繁体   中英

Sorting NSArray containing NSDate objects

I have an array containing NSDate objects. With Objective-C, I am able to sort this array by using:

NSArray *array = [unsortedArray sortedArrayUsingSelector:@selector(compare:)]

I'm wondering if there's a Swift equivalent of doing this same thing. Relatively new to Swift here, hacking my way through.

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"]

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM