SwiftData Aggregate

Given a simple class:

final class Person {
   name: String
   age: Int
}

How can I get aggregated data such as average age, or count of people within specific ranges?

If you have, say:

@Query var people: [Person]

Then you can get average age like this:

people.lazy.map(\.age).reduce(0) { $0 + Double($1) } / people.count

And you can get the number of people within an age range like this:

people.lazy.filter { range.contains($0.age) }.count

Hope that helps.

1 Like

I was hoping to do it at the database level, not my code level. Thanks for the information, definitely helpful if I can't do it at the database level.