Sorting NSArray containing NSDate objects

后端 未结 3 1147
暗喜
暗喜 2020-12-11 22:06

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

NSArray *array = [unsortedArray sortedArrayU         


        
3条回答
  •  感情败类
    2020-12-11 22:41

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

提交回复
热议问题