Search code examples
swiftrealm

Why RealmCollectionType methods return Results and not RealmCollectionType/AnyRealmCollection?


I recently moved from Array to RealmCollectionType because it provides more effective filters. Now I want to migrate my unit-tests as well, but I don't like the In-memory Realm because it requires me to setup a lot of links and relations between my objects. I was trying to mock Results and LinkingObjects by conforming my mock to RealmCollectionType. Unfortunately, I'm stuck implementing filter operation because it should return Results which is declared as final.

What is the purpose of filters to narrow it's return type to Results?


Solution

  • RealmCollection.filter(...) returns a Results because that's the query result container in Realm. It does share some common interface elements with other collection types in Realm (like LinkingObjects and List), which is why it conforms to the RealmCollection protocol.

    If you'd like to test code that's generic on say the Collection protocol in the Swift standard library, which RealmCollection inherits from, you can do so.