Sort NSArray with NSDate objects

I have an array containing objects NSDate. With Objective-C, I can sort this array using:

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

I am wondering if there is a Swift equivalent for doing the same. Relatively new to Swift here, hacking my way.

+4
source share
3 answers

Using native type Arrayin Swift. If you are interacting with obsolete code from ObjC, use this:

let array = unsortedArray.sortedArrayUsingSelector("compare:")
+1
source

If you are using a 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)
+2
source

NSDate Comparable, , :

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"]
+2
source

Source: https://habr.com/ru/post/1621921/


All Articles