Page A SwiftData Feed With A Stable Cursor

A feed loads its first thirty entries. Someone deletes an entry near the top. The next fetch skips thirty rows and starts one row too far down.

Nothing crashed. One entry simply lost its invitation to the list.

An offset describes a position in the results when that fetch runs. For a newest-first activity feed, we can instead remember the last entry delivered and ask for entries that sort after it. This is keyset pagination, often called cursor pagination.

We’ll build a small SwiftData reader with a stable two-part cursor, then give its caller explicit refresh and end-of-results behavior. The example targets iOS 18 / macOS 15 or later, uses Swift 6.4.2 in Xcode 27.2, and reads an existing local store. It doesn’t implement downloading or synchronization.

Decide what should stay still

Consider these entries, all sharing the same publication time, ordered by a unique server ID:

OperationResult
First page, size three8, 7, 6
Delete entry 8Store now begins 7, 6, 5, 4, 3…
Next page with offset three4, 3, 2 — entry 5 was skipped
Next page after ID 65, 4, 3

Inserting ahead of the first page creates the opposite problem: an offset can return an entry you’ve already delivered. A boundary based on saved values stays useful even when the boundary’s own row is deleted.

This is a good fit for browsing an activity history whose ordering fields stay fixed. It is a different product choice from a live query that continuously inserts, removes, and rearranges the visible results. Apple’s WWDC26 SwiftData Group Lab recommends measuring what you fetch and avoiding objects your screen doesn’t need. Pagination helps control each request; it doesn’t make every query cheap.

Make the ordering unambiguous

Dates alone are not unique. If a page ends halfway through several entries with the same timestamp, a strict date-only comparison skips the rest of that group. An inclusive comparison returns previous entries again.

Use the same two fields in both the ordering and the cursor: publication time descending, then server ID descending. Here the server already supplies a stable, unique Int64 ID. The ID breaks ties; it does not need to increase with time.

Put the three Swift blocks in one file, in order.

import Foundation
import Observation
import SwiftData

@Model final class TimelineEntry {
    #Index<TimelineEntry>([\.publishedAt, \.serverID])
    @Attribute(.unique) var serverID: Int64
    var publishedAt: Date
    var title: String

    init(serverID: Int64, publishedAt: Date, title: String) {
        self.serverID = serverID
        self.publishedAt = publishedAt
        self.title = title
    }
}

nonisolated struct TimelineCursor: Equatable, Sendable {
    let publishedAt: Date
    let serverID: Int64
}

nonisolated struct TimelineRow: Identifiable, Equatable, Sendable {
    let id: Int64
    let publishedAt: Date
    let title: String
}

nonisolated struct TimelinePage: Sendable {
    let rows: [TimelineRow]
    let nextCursor: TimelineCursor?
}

nonisolated enum TimelineError: Error {
    case invalidPageSize
}

The ingestion code must keep both ordering fields unchanged after insertion, reject invalid dates, and preserve ID uniqueness. SwiftData needs mutable stored properties here; that doesn’t give the importer permission to rewrite the ordering on every refresh. Titles may change, but an already-delivered value won’t update automatically.

The compound index is why this example starts at iOS 18. Apple’s index guidance describes this schema feature; inspect the query plan for your actual store before making performance claims. This example uses a local store with CloudKit disabled. Its unique attribute is not a CloudKit synchronization design.

Fetch one extra entry, then keep the right boundary

For descending order, an entry follows our cursor if its date is older, or its date is equal and its ID is smaller. Put that condition in the fetch rather than filtering a fully loaded array.

@MainActor
func fetchTimelinePage(
    in container: ModelContainer,
    after cursor: TimelineCursor? = nil,
    pageSize: Int = 30
) throws -> TimelinePage {
    guard (1...200).contains(pageSize) else {
        throw TimelineError.invalidPageSize
    }

    let context = ModelContext(container)
    context.autosaveEnabled = false
    var descriptor = FetchDescriptor<TimelineEntry>(sortBy: [
        SortDescriptor(\.publishedAt, order: .reverse),
        SortDescriptor(\.serverID, order: .reverse)
    ])
    if let cursor {
        let date = cursor.publishedAt
        let id = cursor.serverID
        descriptor.predicate = #Predicate<TimelineEntry> {
            $0.publishedAt < date ||
            ($0.publishedAt == date && $0.serverID < id)
        }
    }
    descriptor.includePendingChanges = false
    descriptor.fetchLimit = pageSize + 1

    let fetched = try context.fetch(descriptor)
    let rows = fetched.prefix(pageSize).map {
        TimelineRow(id: $0.serverID, publishedAt: $0.publishedAt,
                    title: $0.title)
    }

    let nextCursor: TimelineCursor?
    if fetched.count > pageSize, let last = rows.last {
        nextCursor = TimelineCursor(publishedAt: last.publishedAt,
                                    serverID: last.id)
    } else {
        nextCursor = nil
    }
    return TimelinePage(rows: rows, nextCursor: nextCursor)
}

The extra result answers whether another entry existed at this fetch. The cursor comes from the last delivered row, not that extra row. Otherwise the lookahead entry becomes the next thing we accidentally skip.

Apple documents fetchLimit as the maximum returned model count and includePendingChanges as the switch for matching unsaved context changes. We create a fresh reader context and return value snapshots, so the page doesn’t retain models from a dirty editor context. Save successful imports before expecting these reads to see them.

Keith Harrison’s explanation of pending SwiftData changes is useful background for this boundary. The early iOS 17 bugs it documents were fixed in 17.4; they aren’t the reason offsets shift when a collection changes.

The function runs synchronously on MainActor. Limiting results is not a background-execution strategy or a frame-time guarantee. Profile the actual fetch, especially with relationships or expensive predicates, before putting it on an interaction path. The returned values can cross an actor boundary if you later give the reader its own correctly isolated persistence owner.

Keep failure from advancing the page

An optional cursor needs one more bit of caller state: nil can mean “start from the beginning” or “the previous fetch reached the end.” Calling the reader again with nil after finishing would restart the feed.

This owner remembers that distinction and only changes its rows and boundary after a successful fetch:

@MainActor @Observable
final class TimelinePager {
    private let readPage: (TimelineCursor?) throws -> TimelinePage
    private var cursor: TimelineCursor?

    private(set) var rows: [TimelineRow] = []
    private(set) var hasMore = true

    init(container: ModelContainer, pageSize: Int = 30) {
        readPage = { cursor in
            try fetchTimelinePage(
                in: container, after: cursor, pageSize: pageSize
            )
        }
    }

    init(readPage: @escaping (TimelineCursor?) throws -> TimelinePage) {
        self.readPage = readPage
    }

    func loadMore() throws {
        guard hasMore else { return }
        let page = try readPage(cursor)
        rows.append(contentsOf: page.rows)
        cursor = page.nextCursor
        hasMore = cursor != nil
    }

    func refresh() throws {
        let page = try readPage(nil)
        rows = page.rows
        cursor = page.nextCursor
        hasMore = cursor != nil
    }
}

Create one pager at your screen’s ownership boundary, using the existing container that includes TimelineEntry. For a standalone local fixture, configure that container with ModelConfiguration(cloudKitDatabase: .none). Call loadMore() for the first page and subsequent pages, and offer refresh() as the explicit return to the newest entries. Catch thrown errors in the interface, keep the existing rows visible, and offer a retry of the failed operation.

The second initializer lets a test inject a reader that throws after a successful page. It can then verify that a retry uses the same cursor and that a failed refresh leaves the existing rows intact.

A successful refresh replaces the current browsing session. It doesn’t preserve an arbitrary scroll position or merge newer rows into the existing history. These reads are synchronous, so this sample doesn’t need a concurrent-request scheduler. Adding asynchronous loading would also require request ownership and stale-result handling.

Each read returns at most pageSize values. The pager retains every delivered page, so its total memory still grows as someone browses. Use a separate windowing policy if that needs a bound.

Test the boundary, including its limits

The downloadable sample and checks exercise the exact article code against a disk-backed store. The important cases are:

  • Multiple pages of tied timestamps, including ties across a page boundary.
  • An insertion or deletion ahead of the cursor, with an offset-based negative control.
  • Deleting the cursor’s own row before requesting the next page.
  • Empty stores, exact page-size totals, a one-row tail, and repeated calls after the end.
  • Unsaved versus saved inserts, process reopen, and a failed read that retains the paging state.
  • Backdated inserts and changes to ordering fields, which demonstrate the limits below.

The exact code compiles with warnings treated as errors for the minimum deployment targets, in ordinary and MainActor default isolation. The disk-backed checks also pass in both modes on macOS 27.2 and an iOS 27.2 simulator, including separate-process reads. This doesn’t establish older-OS behavior, physical-device performance, or a complete scrolling interface.

A cursor is not a snapshot of the entire database. Entries inserted below the current boundary may appear later. Entries inserted above it wait for a refresh. A backdated entry inserted into an already-traversed range can be missed. Changing a previously delivered entry’s ordering fields can cause it to appear again. Keep the ordering immutable and decide whether those insertion semantics suit your product.

Likewise, hasMore == false means the last fetch found no lookahead row. It doesn’t promise that another writer will never add one. Refresh starts a new traversal. Reset the pager when the account, store, filter, or sort contract changes; don’t reuse a cursor across those boundaries.

Use a live @Query when the screen should continually reflect edits and deletions. Use this reader when it should advance through stable ordering boundaries, with an explicit refresh. The useful guarantee is small and concrete: removing an earlier row doesn’t change what “after this entry” means.