Swift Filter Embedded Objects

Can a Swift filter be run against embedded objects?

For example: say you have a Person with a list of embedded dogs, with each dog having an age property

class Person: Object {
   let dogs = List<EmbeddedDog>()
}

class EmbeddedDog: EmbeddedObject {
     ... age = 0
}

and suppose there are 3 dogs embedded in a person object with ages 1, 2 and 3.

This works

let results = person.dogs.filter("age > 1")

and returns dogs with ages 2 and 3. Wheras this

let results = person.dogs.filter { $0.age > 1 }

returns all of the dogs in the list. Even if the 1 is changed to 100, it has the same behavior and all dogs are returned.

Yes, you can filter on embedded objects, but the syntax is a little different. Here’s a snippet from one of my apps…

@ObservedResults(Rate.self) var rates
    
let baseSymbol: String
let symbol: String
    
var rate: Rate? {
    rates.filter(
        NSPredicate(format: "query.from = %@ AND query.to = %@", baseSymbol, symbol)).first
}

You can find the full app in this repo and this post talks about it.

Thanks @Andrew_Morgan1

I believe the ObjC NSPredicate in your example is still filtering using a Realm filter using an ObjC NSPredicate.

The goal is to use Swift High Order functions to filter (or a Swift map or reduce etc) as shown in my second example.

Swift filters work fine in general on Lists and Results when they contain ‘regular’ Realm objects but we are not seeing it work with Embedded objects - hence the question.

We understand the downsides of filtering Realm with Swift filters due to loosing the lazy-loadingness of Realm objects but we have a use case where it’s small amount of static data.

As an example:

If we have a object

class Dog: Object {...

and the Person object has a list of dogs

class Person: Object {
   let dogs = List<Dog>()
}

this code works

let results = person.dogs.filter { $0.age > 1 }

and the results contains all the dogs with ages > 1

However, as mentioned in the original post if the Dog is an Embedded object, that same code returns all dogs, not just dogs with ages > 1. Along with that other Swift high order functions also seem to behave oddly with Embedded objects (map, reduce etc)

Jay

@Andrew_Morgan Any thoughts on this as I am not seeing Swift functions function on Embedded objects correctly (like they do on regular Realm objects)

Very strange. A clean and rebuild corrected the issue.