简体   繁体   English

对包含NSDate对象的NSArray进行排序

[英]Sorting NSArray containing NSDate objects

I have an array containing NSDate objects. 我有一个包含NSDate对象的数组。 With Objective-C, I am able to sort this array by using: 使用Objective-C,我可以使用以下方法对此数组进行排序:

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

I'm wondering if there's a Swift equivalent of doing this same thing. 我想知道是否有Swift等同于做同样的事情。 Relatively new to Swift here, hacking my way through. 对Swift来说相对较新,黑客入侵。

If you use Swift array. 如果你使用Swift数组。

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: 您可以使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"]

Using the native Array type in Swift. 在Swift中使用本机Array类型。 If you are interfacing with legacy code from ObjC, use this: 如果您与ObjC的旧代码连接,请使用以下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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