How to sort using Realm?

Cody Weaver picture Cody Weaver · Dec 15, 2015 · Viewed 30.7k times · Source

I don't know how to sort using Realm. My current code is.

data = realm.objects(WorkoutSet)
data = data!.sorted("date")

I want to sort date an Int from high numbers to low numbers. The docs need more information and the GitHub link throws a 404 message.

Answer

joern picture joern · Dec 15, 2015

You can add an ascending parameter to the sorted method:

data = data!.sorted("date", ascending: false)

This sorts your WorkoutSet using the date field in descending order.

Update

With Swift 3 and the latest RealmSwift version this has now changed to:

data = data!.sorted(byKeyPath: "date", ascending: false)

If you want to evaluate the sort criteria yourself you could use:

data = data!.sorted(by: { (lhsData, rhsData) -> Bool in
   return lshData.something > rhsData.something
})

But be aware that sorting your results by yourself does return an Array instead of a Realm Results object. That means there will be a performance and memory overhead, because Results is lazy and if do the sorting with the above method you will lose that lazy behavior because Realm has to evaluate each object! You should stick to Results whenever possible. Only use the above method if there really is no other way to sort your items.