Skip to main content

How to count results without loading them

About 1 minSwiftArticle(s)bloghackingwithswift.comcrashcourseswiftswiftdataxcodeappstore

How to count results without loading them 관련

SwiftData by Example

Back to Home

How to count results without loading them | SwiftData by Example

How to count results without loading them

Updated for Xcode 15

A regular SwiftData query loads all matchings objects into memory for immediate use, but sometimes you don't actually need the data because you just want to show how many matches there were.

For times like this, you should use the fetchCount() method of your model context. This returns how many objects matches your predicate without loading those objects into memory, which means it executes several orders of magnitude faster and uses almost no memory.

As an example, if you wanted to know how many employees had a salary over $100,000 you should prefer to write this:

let descriptor = FetchDescriptor<Employee>(predicate: #Predicate { $0.salary > 100_000 })
let count = (try? modelContext.fetchCount(descriptor)) ?? 0

That does the entire counting in the database, wasting no time or memory.

In contrast, using a regular fetch then performing a count loads all the objects into memory for no real reason. So, this kind of code is a bad idea:

let descriptor = FetchDescriptor<Employee>(predicate: #Predicate { $0.salary > 100_000 })
let objects = (try? modelContext.fetch(descriptor)) ?? []
let count = objects.count

이찬희 (MarkiiimarK)
Never Stop Learning.