Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm query sum of property

I'm using RealmSwift and I have a realm object called Book

Book
=====
title: String
pageCount: Int

when the app starts I get all the books using:

allBooks = realm.objects(Book)

a Book has a realm property called pageCount

I'm trying to understand how can I get the total pages count for all the books?

So if I have book A with 3 pages, book B with 11 pages and book C with 0 page the total count will be 3+11+0 = 14

I prefer doing it with a query and not iterate through all the books

like image 355
Mario Avatar asked Jul 09 '15 13:07

Mario


2 Answers

You can get the total number of pages for all your book objects as follows:

let totalPages: Int = realm.objects(Book).sum("pageCount")
like image 188
segiddins Avatar answered Nov 16 '22 13:11

segiddins


Swift 4+:

let totalPages: Int = realm.objects(Book.self).sum(ofProperty: "pageCount")
like image 4
jamryu Avatar answered Nov 16 '22 14:11

jamryu