Realm Swift: always put nil values last in sort

后端 未结 2 1012
遥遥无期
遥遥无期 2021-01-11 23:59

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(_:ascendin

2条回答
  •  青春惊慌失措
    2021-01-12 00:43

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

提交回复
热议问题