Как я могу применить пользовательскую сортировку к этому массиву объектов? - PullRequest
0 голосов
/ 07 июня 2018

У меня есть коллекция объектов, где я хочу отсортировать объект по SortDate, где SortDate сортируется по дате, самой новой к текущей дате, затем от будущей даты к прошлой дате.Например, если мой массив Events содержит объекты с SortDate, равным 4 июня, 8 июня и 20 июня. Я хочу отсортировать его так, чтобы сначала отображалось 8 июня, затем 20 июня, а затем 4 июня. Где 8 июня ближе всего к сегодняшней дате 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! }

Ответы [ 2 ]

0 голосов
/ 07 июня 2018

вы можете использовать это, предполагая, что все ваши опции даты не равны нулю.

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))
}
0 голосов
/ 07 июня 2018

Вы можете отсортировать массив, используя Функция сортировки массива (по :) .

Вот пример:

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
    }
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...