osrl
osrl

Reputation: 7828

How to write a Realm Results object extension

I want write an extension that simplifies a complex filtering on my Results object. I tried this:

extension Results where T:MyProtocol {
    func filterEnabled() -> MyProtocol {
        return self.filter("type == 1").filter { $0.enabled == true }
    }
}

XCode gives me this error: Ambiguous reference to member 'filter'. I think T:MyProtocol constraint is not enough.

How can I accomplish what I'm trying to do?

Upvotes: 0

Views: 1162

Answers (1)

marius
marius

Reputation: 7806

I think the problem here is not the generic constraint, but that both filter methods, you're using here return a collection, which doesn't match the return type you specified.

That's also important to note: The first filter you apply can be optimized internally by Realm to query your database, the latter is part of the Swift standard library and pulls all objects into memory first before filtering them.

extension Results where T: Named {
    func firstEnabled() -> Named? {
        return self.filter("type == 1 && enabled == true").first
    }

    func filterEnabled() -> Results<T> {
        return self.filter("type == 1 && enabled == true")
    }
}

Upvotes: 3

Related Questions