Search code examples
swiftsortingrealmkeypaths

How do I sort Realm Results by a keypath of the first item in a to-many relationship?


My model has an GroupOfEvents realm object that has a to-many relationship to Event realm object via the property events. Each Event has a date property.

I have a Results<GroupOfEvents> and I want to sort by the date of the first event in events. If I were sorting a regular swift array, it would look like:

groupsOfEvents.sorted(by: { $0.events.first!.date > $1.events.first!.date })

Here is my failed attempt to sort a Results<GroupOfEvents>:

groupsOfEvents.sorted(byKeyPath: "events.first.date")

It gives the error:

'Cannot sort on key path 'events.first.date': property 'GroupOfEvents.events' is of unsupported type 'array'.'

How can I sort it the way I want?


Questions you might ask me:

Why are you sorting by the first event's date? That's not something people usually do.

In fact, GroupOfEvents contains events with the same date, so using the date of any event in events will work.

Why don't you just move the date property to GroupOfEvents?

Yes, I could do that, but I am looking for alternatives to that.

Why don't you get rid of GroupOfEvents and just get all the Events then group by the date?

Although all events in a GroupOfEvents have the same date. The events of two different GroupOfEvents can have the same date as well. There are other properties that differentiates GroupOfEvents.


Solution

  • From Realm's header files I see this comment:

    Collections may only be sorted by properties of boolean, Date, NSDate, single and double-precision floating point, integer, and string types.

    That means that your array of events is not a supported key-path, just as the error you are receiving is saying.

    Update

    Based on this answer you can cast an object of type Results to an array. So you could try something along these lines:

    let groupsOfEventsSortedArray = Array(groupsOfEvents).sorted { $0.events.first!.date > $1.events.first!.date }