Red
Red

Reputation: 1

How can I sort dates in swift realm repository using my own comparator?

Context: I saved a list of objects in realm repository. These objects contain a property of standard type Date. I would like to get a list of those objects back from Realm based on distinct dates which means in other words : If two objects in realm have the same date, I only want to return the first object and not the second one. If 4 objects have the same date, I only want to return the first one and not the three others. So at the end, my final result from Realm will only contain a list of objects with distinct/unique dates. Basically I could simply use this line of code :

realm.objects(type.self).distinct(by: [key])

where :

My problem: I would like to compare dates based only on Day value : if two dates have the same day value they should be considered the same date, else they should be considered different dates. However, since Date is part of Foundation library I can't change the == method to specify my own comparison result.

I have tried to create a sort descriptor with my own comparator using this initialiser :

NSSortDescriptor(key: String , ascending: bool, comparator: Comparator)

where comparator could be a closure returning my own Comparison result. However I can't sort realm results with NSSortDescriptor directly, I need to convert it to SortDescriptor. SortDescriptor can be initialised with NSSortDescriptor like this:

let nsSortDescriptor = NSSortDescriptor(key: myKey, ascending: true, comparator: myComparator)
let sortDescriptor = SortDescriptor(keyPath: nsSortDescriptor.key , ascending: nsSortDescriptor.ascending)

As you can see, this initialiser does not provide a comparator input parameter which means I can't specify my own comparator inside SortDescriptor initialiser. How can I use my own comparator inside SortDescriptor ?

Upvotes: 0

Views: 78

Answers (0)

Related Questions