Sanniv Khare 7 min read

Core Data to SwiftData: porting a ledger model, built and tested

Core Data to SwiftData: porting a ledger model, built and tested

Porting a Core Data model to SwiftData is mostly a rename, and the behaviour that matters for money held up: in our tests both stores enforced one account per number, both upserted a duplicate without losing its entries, and both cascaded a delete the same way. Two things did not carry over. A test that read mainContext from a ModelContainer it did not keep crashed with no message, and inserting 5,000 related rows took about 5.4 s in SwiftData against 41 to 64 ms in Core Data on the same Mac.

What to do: port the model, then keep a strong reference to every ModelContainer you create (tests included), and time your largest import before you ship it.

We built one Swift package with the same ledger in both frameworks and ran it on our M1 lab Mac (macOS 15.7.3, Xcode 26.2, Swift 6.2.3): a clean release build, a report executable run twice, Swift Testing tests, and an iOS Simulator build of the package against the iOS 26.2 SDK. Every number below comes from those runs.

Why we did this: Beacon-type banking apps and Shopkeeper keep a local ledger on the phone, and most of that code was written for Core Data. New screens are SwiftUI, and SwiftData is the store that fits them, so the question is what a port actually costs.

The ledger we ported

Two entities, the shape most finance and shop apps share:

  • Account: number (unique), name, a to-many entries relationship that cascades on delete.
  • Entry: memo, amountMinor (Int64, amounts in paise, never floating point), date, an optional account.

The Core Data side builds its model in code, so the package needs no .xcdatamodeld and both versions sit in plain Swift files. Its store is SQLite at /dev/null: in memory, but with uniqueness constraints enforced, which the in-memory store type does not do. The SwiftData side uses ModelConfiguration(isStoredInMemoryOnly: true).

Core Data entity description next to a SwiftData @Model class

The Core Data model in code and the SwiftData class that replaces it.

What maps one to one

Core Data SwiftData Docs
NSEntityDescription + NSManagedObject subclass @Model final class SwiftData
uniquenessConstraints = [["number"]] @Attribute(.unique) var number (or #Unique on iOS 18) #Unique
NSRelationshipDescription, deleteRule = .cascadeDeleteRule @Relationship(deleteRule: .cascade, inverse:) SwiftData
NSPersistentContainer ModelContainer ModelContainer
viewContext mainContext (main actor) ModelContext
NSFetchRequest + NSPredicate(format:) FetchDescriptor + #Predicate ModelContext
NSSortDescriptor(key: "date", ascending: false) SortDescriptor(\Entry.date, order: .reverse) SwiftData
mergePolicy = .mergeByPropertyObjectTrump Upsert on a unique attribute, built in Core Data

The fetch is where the port reads best. The string predicate, with its key paths checked only at runtime:

let request = NSFetchRequest<CDEntry>(entityName: "Entry")
request.predicate = NSPredicate(
    format: "account.number == %@ AND amountMinor < 0", "ACC-1")
request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
let debits = try context.fetch(request)

becomes a predicate the compiler checks:

let number = "ACC-1"
let debits = try context.fetch(FetchDescriptor<Entry>(
    predicate: #Predicate<Entry> { $0.account?.number == number && $0.amountMinor < 0 },
    sortBy: [SortDescriptor(\Entry.date, order: .reverse)]))

Capture the value in a local constant (number) before the macro; #Predicate builds an expression tree, not a closure over arbitrary code. Optional chaining through the relationship ($0.account?.number) worked as written.

What we ran, and what came back

The report executable does the same five things on each store: insert one account with 5,000 entries, fetch the debits newest first, insert a second account ACC-2 with 3 entries and then insert a duplicate ACC-2 with a new name, count orphans, and delete ACC-1.

Report output: Core Data and SwiftData results side by side, and three SwiftData insert variants

Real output from the second run; the first run gave the same counts and timings within a few percent (Core Data insert 63.6 ms in that run).

The behaviour lines match exactly:

  • Fetch: 1,666 debits in both, newest first, top row Entry 4998 in both.
  • Duplicate unique key: one ACC-2 row in both, name New name in both, and its 3 entries still attached in both. For a ledger this is the result you want: an upsert from a sync payload does not orphan the history.
  • Cascade: after deleting ACC-1, only ACC-2’s 3 entries were left in both stores. No orphans in either.

The test crash: keep the container

Our first SwiftData test looked like the Core Data one:

@Test func swiftDataReturnsDebitsNewestFirst() throws {
    let mc = try SwiftDataLedger.makeContainer().mainContext   // container not kept
    // insert, save, fetch ...
}

swift test built, started the test and then stopped with error: Exited with unexpected signal code 5: no assertion message, no stack in the output. The uniqueness test, written the same way, did the same. The Core Data test, which also takes viewContext straight off a container it does not keep, passed.

Our reading of the difference is ownership. A Core Data context keeps its persistent store coordinator alive. A SwiftData ModelContext does not keep its ModelContainer alive, so the container is released at the end of that expression and the next call on the context traps. Holding the container fixed all three tests:

@Test func swiftDataReturnsDebitsNewestFirst() throws {
    let container = try SwiftDataLedger.makeContainer()
    let mc = container.mainContext
    // insert, save, fetch ...
}
✔ Test swiftDataReturnsDebitsNewestFirst() passed after 0.015 seconds.
✔ Test bothStoresKeepOneAccountPerNumber() passed after 0.015 seconds.
✔ Test coreDataReturnsDebitsNewestFirst() passed after 0.015 seconds.
✔ Test run with 3 tests in 1 suite passed after 0.016 seconds.

In an app this rarely bites, because .modelContainer(...) on the scene holds it. It bites in tests, previews and helper functions that return a context, which is exactly where a port adds new code. Return the container, or store it, and take mainContext from it where you use it.

The timings are from one Mac and an in-memory store, so read them as a direction, not a benchmark. Inserting one account and 5,000 entries, each created with Entry(..., account: a), took 5,367 ms and 5,348 ms in SwiftData across the two runs. Core Data did the same work in 40.8 ms and 63.6 ms. The filtered fetch was 1.5 ms against 43.5 ms.

To see where the time goes, the report runs three SwiftData variants, each in a fresh container:

Variant Run 1 Run 2
A: Entry(..., account: a) for each row 5,476 ms 5,525 ms
B: build the array, then a.entries = [...] once 2,612 ms 2,585 ms
C: the same 5,000 entries with no relationship 235 ms 238 ms

Most of the cost is the relationship, not the rows: the same inserts without it took about 0.24 s. Setting the to-many side once from the parent halved the time. For a first sync that pulls months of transactions, that difference is the gap between a spinner and a frozen screen, because mainContext work runs on the main actor.

What we take from it for our own apps:

  • Keep ordinary screens on mainContext; a few hundred rows are not a problem.
  • For bulk imports, assign relationships from the parent in one go (variant B), and save once.
  • Time your own largest import with your real model before you remove the Core Data path. A background ModelActor import is outside this post.

Porting checklist

  1. Write the @Model classes next to the existing Core Data model; keep property names identical so the data maps cleanly.
  2. Translate each uniquenessConstraints entry to @Attribute(.unique) and each delete rule to @Relationship(deleteRule:inverse:).
  3. Translate fetches one by one to FetchDescriptor and #Predicate; capture values in local constants first.
  4. In tests and previews, keep a let container for the whole test.
  5. Port your merge policy last: a unique attribute already upserts, and in our run it kept the children.
  6. Time the biggest import and the busiest fetch on both stores before switching.

The package also built for the iOS Simulator with xcodebuild against the iOS 26.2 SDK (deployment target iOS 18), so the same code serves the phone app and its tests. If you are moving the view layer at the same time, our ObservableObject to @Observable guide covers that half, and default MainActor isolation in Swift 6.2 explains the actor rules that mainContext follows.

Made by the team behind this post

Apps from our studio

  • Goes with this post

    Nix

    The Mac uninstaller that finds what the Trash leaves behind: caches, logs, derived data and saved states.

    macOS

    Get
  • Goes with this post

    Cardigami

    Pop-up greeting cards that rise out of the fold on iPhone Duo.

    iPhone · App Store

    Get
  • Goes with this post

    OneClick QuitAll

    Quit every running app in one click. See memory and CPU first.

    macOS · Mac App Store

    Get
  • BMDB.fun

    Your Bollywood world at a glance, with links straight to the OTT app that streams each film.

    Android TV · Web · Mobile

    Get

Need this built? Let’s talk.

We build and run apps for Mac, TV, mobile and the web, and write about what we learn.