StackOverflower StackOverflower - 8 months ago 106
iOS Question

How to get item with max id?

I'm tryig to get the ítem with max id using this query


It's throwing an error saying that can't parse query so it seems this is not the correct way to do it.

How can I write this query on Realm for Swift?


Filters alone cannot do what you're after as they only consider a single top-level object at a time.

Beyond that conceptual issue, there are a few issues with the code you posted:

  1. @"" is not a valid NSPredicate format string. NSPredicate format strings must be composed of comparisons between expressions, not expressions on their own.

  2. Collection operators such as @max must be applied to a collection. In your example it is being applied to an Entity. Since an Entity is not a collection, the predicate would not be valid. It would be valid to apply a collection operator to a List property on Entity though.

Something like the following should do what you're after:

let entities = realm.objects(Entity)
let id = entities.max("id") as Int?
let entity = id != nil ? entities.filter("id == %@", id!).first : nil