嵌套排序 NSArray
Nested Sorting NSArray
我有一个 NSDates 的 NSArray,我想按这样的方式排序,即日期是递减的,但时间是递增的。
排序后的数组(解释)如下所示:
{tomorrowMorning, tomorrowAfternoon, thisMorning, thisAfternoon, yesterdayMorning, yesterdayAfternoon}
完成此任务的最佳方法是什么。
为日期添加扩展名 -
extension Date {
public func dateWithZeroedTimeComponents() -> Date? {
let calendar = Calendar.current
var components = calendar.dateComponents([.year, .month, .day], from: self)
components.hour = 0
components.minute = 0
components.second = 0
return calendar.date(from: components)
}
}
然后使用这个排序代码 -
// example test data
let dates: [Date] = [Date(timeIntervalSinceNow: -80060), Date(timeIntervalSinceNow: -30), Date(timeIntervalSinceNow: -75000), Date(timeIntervalSinceNow: -30000), Date(timeIntervalSinceNow: -30060)]
let sortedDates = dates.sorted { (date1, date2) -> Bool in
if let date1Zeroed = date1.dateWithZeroedTimeComponents(), let date2Zeroed = date2.dateWithZeroedTimeComponents() {
// if same date, order by time ascending
if date1Zeroed.compare(date2Zeroed) == .orderedSame {
return date1.compare(date2) == .orderedAscending
}
// otherwise order by date descending
return date1.compare(date2) == .orderedDescending
}
return true
}
print(sortedDates)
结果 -
[2017-06-15 05:20:29 +0000, 2017-06-15 05:21:29 +0000, 2017-06-15 13:40:59 +0000, 2017-06-14 15:27:09 +0000, 2017-06-14 16:51:29 +0000]
我想这就是你想要的?
我有一个 NSDates 的 NSArray,我想按这样的方式排序,即日期是递减的,但时间是递增的。
排序后的数组(解释)如下所示:
{tomorrowMorning, tomorrowAfternoon, thisMorning, thisAfternoon, yesterdayMorning, yesterdayAfternoon}
完成此任务的最佳方法是什么。
为日期添加扩展名 -
extension Date {
public func dateWithZeroedTimeComponents() -> Date? {
let calendar = Calendar.current
var components = calendar.dateComponents([.year, .month, .day], from: self)
components.hour = 0
components.minute = 0
components.second = 0
return calendar.date(from: components)
}
}
然后使用这个排序代码 -
// example test data
let dates: [Date] = [Date(timeIntervalSinceNow: -80060), Date(timeIntervalSinceNow: -30), Date(timeIntervalSinceNow: -75000), Date(timeIntervalSinceNow: -30000), Date(timeIntervalSinceNow: -30060)]
let sortedDates = dates.sorted { (date1, date2) -> Bool in
if let date1Zeroed = date1.dateWithZeroedTimeComponents(), let date2Zeroed = date2.dateWithZeroedTimeComponents() {
// if same date, order by time ascending
if date1Zeroed.compare(date2Zeroed) == .orderedSame {
return date1.compare(date2) == .orderedAscending
}
// otherwise order by date descending
return date1.compare(date2) == .orderedDescending
}
return true
}
print(sortedDates)
结果 - [2017-06-15 05:20:29 +0000, 2017-06-15 05:21:29 +0000, 2017-06-15 13:40:59 +0000, 2017-06-14 15:27:09 +0000, 2017-06-14 16:51:29 +0000]
我想这就是你想要的?