Search code examples
iosswiftfilterrealm

Filter on first letter of property


I've got a local db (Realm) with drinks. Each drink has a name.

I want to get all the drinks starting with a certain letter.

This is what I came up with:

let objects = realm.objects(Drank.self)
                   .filter{($0.name.characters.first)?.description == section}

The problem I am having now is that the objecttype I get is a 'LazyFilterBidirectionalCollection'. But I need Results.

Does anybody know a way to convert it to the correct type or maybe a different way to filter the resultset?


Solution

  • This is straight from the realm docs on sorting/filtering:

    let sortedDogs = realm.objects(Dog.self).filter("color = 'tan' AND name BEGINSWITH 'B'").sorted(byProperty: "name")
    

    So to filter something you are looking for maybe something like this:

    let objects = realm.objects(Drank.self)
                   .filter("name BEGINSWITH '\(column)'")
    

    A safer option proposed below by Thomas Goyne,

    let objects = realm.objects(Drank.self)
                   .filter("name BEGINSWITH %@", column)
    

    Since you are now filtering data with the way the docs use you should receive a Results object

    Don't be afraid to read documentation, not only will you be able to get the satisfaction of figuring it out on your own, you will also learn a bunch of other things along the way.