Home > Net >  realm swift - filter objects with a property that starts with a string included in a list
realm swift - filter objects with a property that starts with a string included in a list

Time:05-01

I have a list of strings

filterList = ['x0', 'x1', 'x2']

My object is as follows:

class Item: Object {
    @Persisted var name: String?
}

I want to get all objects with a name that starts with one of the list elements (x0 or x1 or x2)

So an object with a name x072 or x1e2 will be included in the result but an object with a name x933 or y011 will not

Thank you

CodePudding user response:

There are a number of ways to do that. One option (which is not really practical in this use case) is to use the Realm Swift Query UI

let results2 = realm.objects(Item.self).where {
    $0.name.starts(with: "x0") ||
    $0.name.starts(with: "x1") ||
    $0.name.starts(with: "x2")
}

As you can see, for a few items it's ok. What if there are dozens? Not very practical. That's where a NSCompoundPredicate really shines. Check this out

var predicateArray = [NSPredicate]()

for name in ['x0', 'x1', 'x2'] {
    let predicate = NSPredicate(format: "name BEGINSWITH[cd] %@", name)
    predicateArray.append(predicate)
}

let compoundPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicateArray)

let results = realm.objects(Item.self).filter(compoundPredicate)

Way more practical as the elements in the list can be as many as needed.

There are some other options as well but the NSPredicate route is suggested in this use case.

  • Related