skip to content

With SwiftData's FetchDescriptor, how do you page through a large book list and show a total count without loading every Book?

level: middleimportance: should knowfreq 50%

answer

  1. limit plus offset
  2. a sort that never ties
  3. count without materialising models
  4. count before you set the limit

basics

~20 s

Set fetchLimit and fetchOffset on a FetchDescriptor with a stable sort and pass it to the context's fetch(:) for each page. For the badge call fetchCount(:) on a descriptor without a limit, which returns an Int without building any models.

solid answer

~40 s

A `FetchDescriptor<Book>` carries a `predicate`, `sortBy`, and options. For paging set `fetchLimit` to the page size and `fetchOffset` to `page * pageSize`, and sort on keys that give a total order, because offset paging is only as stable as the sort. `modelContext.fetchCount(descriptor)` returns the number of matches as an `Int` instead of models; build that count from the descriptor before you set the limit, since a count also respects `fetchLimit`. To cut the cost per row, `propertiesToFetch` limits which attributes load and `relationshipKeyPathsForPrefetching` pulls related models such as each book's author in the same fetch. Leave `fetchLimit` as `nil` for all results, and remember `includePendingChanges` is `true` by default, so unsaved inserts are counted.

code

swift · 17 lines
swift
import SwiftData
import Foundation

func loadPage(_ page: Int, genre: String, in context: ModelContext) throws -> (books: [Book], total: Int) {
    let pageSize = 20
    var descriptor = FetchDescriptor<Book>(
        predicate: #Predicate { $0.genre == genre },
        sortBy: [SortDescriptor(\.title), SortDescriptor(\.published)]
    )
    let total = try context.fetchCount(descriptor)  // counted before a limit is set

    descriptor.fetchLimit = pageSize
    descriptor.fetchOffset = page * pageSize
    descriptor.propertiesToFetch = [\.title, \.published]
    descriptor.relationshipKeyPathsForPrefetching = [\.author]
    return (try context.fetch(descriptor), total)
}

go deeper

for a junior

Know that FetchDescriptor holds a predicate and sort and that the context's fetch(_:) runs it; fetchCount returns a number.

for a middle

Explain fetchLimit and fetchOffset with their nil and 0 defaults, why paging needs a total-order sort, and that a count honours the limit.

for a senior

Talk through propertiesToFetch, relationship prefetching and batch fetching for a slow list, how pending changes affect counts, and why a count never reuses a paged descriptor.

for a principal

Weigh offset paging against walking a sorted key for large, frequently edited stores, and decide what a list really needs to load per row.

## FetchDescriptor in one paragraph **`FetchDescriptor<T>`** is the value that tells a SwiftData model context *what* to fetch. It is created with `init(predicate:sortBy:)`, both optional, and exposes mutable properties for the rest. You pass it to `ModelContext.fetch(_:)` for an array of models, to `fetchCount(_:)` for a number, or to the `@Query(_:)` macro when a SwiftUI view should own the fetch. With no predicate it matches every model of its type; it always fetches a single model type. | Property | Default | What it does | |---|---|---| | `predicate` | from the initializer | which models match | | `sortBy` | `[]` | sort descriptors, applied in array order | | `fetchLimit` | `nil` | maximum number of models returned | | `fetchOffset` | `0` | how many matching models to skip first | | `includePendingChanges` | `true` | match unsaved changes in the context too | | `propertiesToFetch` | `[]` | attributes to load; empty means all | | `relationshipKeyPathsForPrefetching` | `[]` | related models to load in the same fetch | ## Paging with limit and offset For a library of thousands of books, a page of twenty is a descriptor with `fetchLimit = 20` and `fetchOffset = page * 20`. Apple's documentation describes the pair as the way to cut a large result into smaller, more efficient batches: an offset of 1 over A, B, C, D returns B, C, D, and an offset of 4 returns nothing. Rules that keep pages correct: 1. **Always sort.** Without `sortBy` nothing defines which twenty books are "page 3". 2. **Sort to a total order.** If many books share a title, add a second key such as the publication date, because the API promises nothing about how ties are ordered between two fetches. 3. **Use `nil`, not `0`, for no limit.** The documentation is explicit that `nil` is what returns all models. 4. **Expect drift under edits.** Offset paging counts positions, so an insert before the current page shifts later pages by one; reload or page on a sort key when that matters. ## Counting without loading `fetchCount(_:)` returns the number of models that satisfy the descriptor as an `Int`. It does not hand back model objects, which makes it the right call for a badge such as "1,284 books". Three details matter: - **The count respects `fetchLimit` and `fetchOffset`.** Counting the same descriptor you use for a page of twenty returns at most twenty. Take the count first, or from a copy without the limit. - **Never count a descriptor that has an offset but no limit.** `fetch(_:)` accepts that combination, but in a run on the current SDK `fetchCount(_:)` stopped the app with an uncaught exception: "Invalid SQL (must specify a limit with an offset)". - **Pending changes count.** With `includePendingChanges` left at `true`, a book inserted but not yet saved is included. Set it to `false` to count only what is persisted. ## Making each row cheaper - **`propertiesToFetch`** lists the attributes a screen needs, for example `[\.title, \.published]`. The fetch returns values only for those; touching another attribute later costs an extra trip to the store. An empty array means *all* attributes. - **`relationshipKeyPathsForPrefetching`** names relationships to load up front, for example `[\.author]`. Without it, a list that shows each book's author name may trigger one extra fetch per row. - **`fetch(_:batchSize:)`** returns a `FetchResultsCollection` that loads models batch by batch as you index into it, useful when you must walk a large result. `enumerate(_:batchSize:allowEscapingMutations:block:)` walks one, with a default batch size of 5000. ## Which call to use - **`fetch(_:)`** returns `[Book]`; use it when you will read the models. - **`fetchCount(_:)`** returns an `Int`; use it for badges, empty states and "is there anything to sync" checks. - **`fetchIdentifiers(_:)`** returns `[PersistentIdentifier]` without the models, handy when other code will look the models up itself. - **`fetch(_:batchSize:)`** returns a collection filled in batches for walking very large results. An empty-state check is the classic misuse: fetching every book to test `isEmpty` loads the whole table, while `fetchCount` on a descriptor with `fetchLimit = 1` answers the same question by counting at most one match. ## The same descriptor in a view `@Query` has overloads that take a `FetchDescriptor`, which is how a SwiftUI list gets a limit: build the descriptor in a static property, set `fetchLimit`, and write `@Query(Self.newestFive)`. The descriptor is read when the property is created, so turning pages in a view means rebuilding the query from new inputs rather than mutating it. ```swift var descriptor = FetchDescriptor<Book>(sortBy: [SortDescriptor(\.published, order: .reverse)]) descriptor.fetchLimit = 5 ``` Note the `var`: the limit is a mutable property, so a descriptor declared with `let` cannot have it set afterwards.

  • Why might fetchCount report fewer books than the badge should show?
    Because it counts what the descriptor describes, including `fetchLimit` and `fetchOffset`. Reusing a page descriptor with a limit of 20 caps the count at 20. Count with a descriptor that has the same predicate and no paging properties, or take the count before you set them; an offset without a limit is worse, since counting it raised an exception in testing.
  • What does propertiesToFetch cost you if a view later reads an attribute you left out?
    The model still answers, but reading a non-fetched attribute makes SwiftData go back to the store for it, which is the overhead the option was meant to avoid. List exactly what the screen reads, and remember that an empty array means all attributes rather than none.

  • Setting fetchLimit to 0 is how you ask for every model.
  • fetchCount ignores fetchLimit, so any descriptor gives the total.
  • Offset paging is safe without a sort because the store keeps insertion order.
  • An empty propertiesToFetch fetches no attributes at all.
  • To count books you fetch them all and read the array's count.