Search code examples
swiftrealmresultsetrealm-mobile-platform

How to sort a realm Results based on a boolean property


I have tried the sorting with custom pattern. But as it returns an array. It's not helpful. As I need the return type to be Results.

Ex: Consider following:

class A:Object {
    dynamic var name: String = "abc"
    dynamic var isStrong: Bool = false
}

Now how can I sort the above which will produce Results

I did try

realm.objects(a.self).sorted({ (o1, o2) -> Bool in
    return o1.isStrong && !o2.isStrong
})

This produces a sorted array. But I need a realmResults object. Any kind of help is apreiciated. Thank you. :)


Solution

  • You can use a bool property for sorting a Results instance, but you cannot implement a custom sort function that would return Results. Results only supports sorting based on instance properties of the class or based on several instance properties if you add them to a SortDescriptor.

    Even though you cannot define custom sorting logic, it seems that your current logic only implements a descending sort based on a single bool property, so you can achieve the same results using Realm's built in sorted(byKeyPath:,ascending:) method.

    realm.objects(A.self).sorted(byKeyPath: "isStrong",ascending: false)