Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm: predicate returning LazyFilterCollection - how to convert to Results<T>?

I'm filtering my database query with NSPredicates directly on the database, but then I would like to go further and filter the returned values (Results<T>) with a custom predicate:

elements.filter { (element) -> Bool in
    return ... 
}

this one returns a LazyFilterBidirectionalCollection - how can I use this and get the Results again?

like image 507
swalkner Avatar asked Mar 20 '17 20:03

swalkner


1 Answers

We're tracking adding support for block-based predicates in GitHub issue #2138. This will allow you to perform custom filtering outside of that supported via Realm's built-in primitives.

If you need to sometimes work with a Results<T> and other times work with a LazyFilterBidirectionalCollection you can wrap the values in a type-erased wrapper such as AnyBidirectionalCollection<T>, which forwards any operations to the wrapped type, while hiding the underlying collection.

For instance:

func maybeFilter(results: Results<Foo>) -> AnyBidirectionalCollection<Foo> {
    if (condition) {
        return AnyBidirectionalCollection(results.filter { $0.foo != "bar" })
    }
    return AnyBidirectionalCollection(results)
}
like image 146
bdash Avatar answered Nov 15 '22 05:11

bdash