我有一个对象集合,我想通过SortDate对对象进行排序,其中SortDate按最新日期到当前日期排序,然后从未来日期到过去日期排序。例如。如果我的Events数组包含SortDate等于6月4日,6月8日和6月20日的对象。我想对它进行排序,以便6月8日首先显示6月20日然后6月4日。其中6月8日最接近今天的日期6月6日我该怎么办?
这是我的尝试:
self.eventsArray = Array(self.realm.objects(Event.self).filter("EventType == \"Event\"").sorted(byKeyPath: "SortDate", ascending: false))
let dateObjectsFiltered = self.eventsArray.filter ({ ($0.SortDate?.toDate)! > Date() })
self.eventsArray = dateObjectsFiltered.sorted { return $0.SortDate! < $1.SortDate! }
答案 0 :(得分:1)
您可以使用Array's sort(by:) function自定义数组排序。
以下是一个示例:
import Foundation
struct event {
var SortDate: Date
}
//Create the array
var unsortedArray = [event]()
unsortedArray.append(event(SortDate: Date(timeIntervalSince1970: 1528070400)))
unsortedArray.append(event(SortDate: Date(timeIntervalSince1970: 1528416000)))
unsortedArray.append(event(SortDate: Date(timeIntervalSince1970: 1529452800)))
//Determine the closest date to the current date
let currentDate = Date(timeIntervalSinceNow: 0)
var lowestDiff = -1
var closestDate: Date?
var component:Set<Calendar.Component> = Set<Calendar.Component>()
component.insert(.second)
//Loop through the dates, keep track of the current closest date
for element in unsortedArray {
let dateComponents = Calendar.current.dateComponents(component, from: currentDate, to: element.SortDate)
if (lowestDiff == -1 || (abs(dateComponents.second!) < lowestDiff)) {
lowestDiff = abs(dateComponents.second!)
closestDate = element.SortDate
}
}
//Sort the array
unsortedArray = unsortedArray.sorted(by:
{
//If the closest date is in the comparison, return the closest date as greater.
if (closestDate != nil) {
if ($0.SortDate == closestDate) {
print($0.SortDate)
return true
}
else if ($1.SortDate == closestDate){
print($1.SortDate)
return false
}
}
//Otherwise, compare the dates normally
return $0.SortDate > $1.SortDate
}
)
答案 1 :(得分:1)
你可以使用它,假设你所有的日期选项都不是零。
func days(fromDate: Date, toDate: Date) -> Int {
return Calendar.current.dateComponents(Set<Calendar.Component>([.day]), from: fromDate, to: toDate).day ?? 0
}
let today = Date()
self.eventsArray.sort {
let first = days(fromDate: today, toDate: $0.SortDate!.toDate!)
let second = days(fromDate: today, toDate: $1.SortDate!.toDate!)
return (first >= 0 && second < 0) ? true : ((first < 0 && second >= 0) ? false : (first < second))
}