Search code examples
swiftrealm

How can I apply custom sort to this array of objects?


I have a collection of objects where I want to sort the object by SortDate where SortDate is sorted by date newest to current date then from future date to past date. E.g. If my Events array contains objects with SortDate equal to June 4, June 8 and June 20. I want to sort it so that June 8 is shown first then June 20 then June 4. Where June 8 is closest to today's date June 6. How can I do that?

Here's my attempt:

  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! }

Solution

  • you can use this, assuming that all your date optionals are not nil.

    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))
    }