Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm Swift: always put nil values last in sort

Tags:

swift

realm

I'm writing an app in Swift 2.2 targeting iOS 8 and using Realm. I allow the user to sort objects based on various optional properties using Results.sorted(_:ascending:). This works very well for descending sorts but for ascending sorts, nil values are placed first which doesn't look right. Many database systems have a NULLS FIRST/LAST option and with CoreData, it looks like it's possible to subclass NSSortDescriptor. Is there any way to always put nil values last when sorting in Realm? Even if there's only a hacky strategy, that would be appreciated, too.

like image 385
Hélène Martin Avatar asked May 22 '16 11:05

Hélène Martin


1 Answers

Realm doesn't support custom sorting of Results other than what the Results.sorted(_:ascending:) method gives you. But you can compose this yourself fairly easily by concatenating two queries, maybe even exposing that through a computed property:

var results: [MyModel] {
  let sorted = realm.objects(MyModel).sorted("...", ascending: true)
  return sorted.filter("optionalProperty != nil") +
         sorted.filter("optionalProperty == nil")
}
like image 128
jpsim Avatar answered Nov 16 '22 15:11

jpsim