2026 Swift 6.2 SwiftData: How To Incrementally Refactor The Concurrency Data Layer?

The winning approach is a staged Swift 6.2 SwiftData concurrency refactor: first lock the toolchain and reproduction baseline, then close one risky write path inside a @ModelActor, and only expand after safe-value contracts and rollback checks pass. This applies when an older application must keep shipping without a full persistence-layer rewrite.
This guide is for developers maintaining a Swift 6.2 branch, architects dividing SwiftData ownership, and technical leads who need separate Mac environments for parallel validation. It is not a prescription for putting the entire application behind @MainActor.
Start with the toolchain, not with a global annotation
A failed migration often starts with a broad edit:
@MainActor
final class LegacyStore {
// Existing SwiftData access
}
The project may compile after this change. The interface may then become sluggish because imports, saves, fetches, or migration work now compete with UI tasks on the main actor. Compilation success is not proof that the data layer has a correct ownership model.
The version premise also needs correction before any code changes. The official Xcode release notes identify Xcode 26 as containing Swift 6.2, while Xcode 26.6 contains Swift 6.3. This guide therefore targets a maintenance branch intentionally locked to Swift 6.2. It does not describe the current Swift toolchain, and it does not treat Xcode 18 as an official version in this sequence. See the Xcode 26 release notes before interpreting a diagnostic as a language change.
Swift 6 language mode is also a project decision. It is selected through target and build settings rather than being silently forced onto every older project. The default actor isolation proposal explains how a project can control this behavior through configuration and annotations: Swift Evolution proposal SE-0466.
Before touching the persistence code, record:
- The Swift language mode for every affected target.
- Strict concurrency checking and related compiler settings.
- Default actor isolation settings.
- The Xcode and Swift toolchain used to build the current branch.
- The smallest test or user flow that reproduces the diagnostic or runtime symptom.
- Existing logs, thread samples, and the last known-good revision.
The completion evidence for this stage is not “the warnings look different.” It is a repeatable build and test command, a saved diagnostic set, and a branch that can still reproduce the original behavior.
Choose the write path with the clearest ownership
The first migration target should be a complete operation, not an isolated type. A background import, repeated save operation, or synchronization task is often a better candidate than a random model helper because its owner, inputs, and output can be traced.
Follow one path from its entry point to the final save:
UI action or background trigger
-> application service
-> persistence operation
-> fetch or insert
-> mutation
-> ModelContext.save()
-> result returned to caller
For each point, write down who owns:
ModelContainerModelContext- The live
@Modelinstances - UI state
- The background task
- Cancellation
- Error handling
Then classify the failure before naming it. A compiler diagnostic means the type checker rejected isolation or sendability. An actor-isolation violation means code crossed an isolation boundary incorrectly. Main-thread blocking means work is occupying the UI executor for too long. A real deadlock requires evidence such as a thread sample or call stack showing tasks waiting in a cycle.
A screen that stops responding is not automatically proof of an internal SwiftData database deadlock. @ModelActor gives serialized access to model properties through its actor boundary, but it does not prove that every stall comes from internal lock contention. The ModelContext documentation should be used to verify context ownership and operations rather than to infer a cause from symptoms alone.
A useful first-pass trace is small:
- What value enters the operation?
- Which context reads or changes it?
- Where is the save performed?
- What value leaves the operation?
- Which actor consumes that value?
If the answer includes “the caller passes a live model from another context,” the boundary is already a strong migration candidate.
First commit: close one write boundary with @ModelActor
The first commit should create a narrow actor-backed data service. It should not redesign every repository, move all UI state, or add a global escape hatch.
A minimal shape can look like this:
import SwiftData
@ModelActor
actor ImportStore {
func insertRecord(
title: String,
externalKey: String
) throws -> PersistentIdentifier {
let record = ImportedRecord(
title: title,
externalKey: externalKey
)
modelContext.insert(record)
try modelContext.save()
return record.persistentModelID
}
}
The important property is not the exact type name. The operation receives values needed for the work. It creates, fetches, changes, and saves models within the context owned by the actor. The caller does not send a model instance managed by a different context.
Dependency injection keeps the boundary testable:
protocol Importing: Sendable {
func insertRecord(
title: String,
externalKey: String
) async throws -> PersistentIdentifier
}
extension ImportStore: Importing {}
struct ImportCoordinator {
private let store: any Importing
init(store: any Importing) {
self.store = store
}
func run(title: String, externalKey: String) async throws {
let id = try await store.insertRecord(
title: title,
externalKey: externalKey
)
// Pass the identifier to the next layer.
_ = id
}
}
This is a boundary pattern, not a universal template. A project may need a different initializer, container setup, error model, or testing adapter. The decision is still consistent: the actor owns the persistence operation, while the coordinator owns orchestration.
The ModelActor API documentation describes the public actor-based model access surface. It should not be read as a promise that a macro can directly repair a deadlock. A macro can express an ownership boundary. It cannot diagnose a cycle caused by application-level waiting, an incorrect task lifetime, or an external dependency.
Compare the safe first boundary with common shortcuts
| Decision path | What crosses the boundary | Main benefit | Main risk | Use when |
|---|---|---|---|---|
Narrow @ModelActor write service |
Values, identifiers, or Sendable DTOs | Clear context ownership and a small rollback unit | Requires callers to change their contracts | A single write chain can be isolated |
Global @MainActor annotation |
Existing models, closures, and persistence work | Fast reduction in some compiler diagnostics | UI stalls and hidden serialization | Only when the whole type is genuinely UI-owned |
@unchecked Sendable on legacy objects |
The original object without compiler proof | Few immediate edits | Data races and ownership defects become invisible | Only for a narrowly audited external invariant |
@preconcurrency compatibility edge |
Legacy API usage | Contains an unadapted dependency | Warnings can disappear without safety improving | A third-party boundary cannot yet be changed |
| Synchronous queue or semaphore | A forced handoff between executors | May hide an ordering symptom | Blocking, deadlock, and cancellation failures | Not a default concurrency migration tool |
The table is a decision tool, not a list of equivalent solutions. The actor-backed path is usually the strongest first move when the operation can be made value-in and value-out.
Same day: replace model returns with explicit data contracts
The next change is the input and output contract. A managed model object is not a neutral data transfer value. Its identity, context, relationships, and mutation rules belong to a persistence isolation domain.
Prefer one of these outputs:
PersistentIdentifier- An immutable struct containing display fields
- A result enum with only Sendable associated values
- A domain DTO explicitly conforming to
Sendable - A status value describing the save result
For example:
struct ImportedRecordSummary: Sendable {
let id: PersistentIdentifier
let title: String
}
@ModelActor
actor ImportStore {
func insertSummary(
title: String,
externalKey: String
) throws -> ImportedRecordSummary {
let record = ImportedRecord(
title: title,
externalKey: externalKey
)
modelContext.insert(record)
try modelContext.save()
return ImportedRecordSummary(
id: record.persistentModelID,
title: record.title
)
}
}
PersistentIdentifier is designed to represent model identity across SwiftData operations. The official PersistentIdentifier documentation is the correct reference for its public semantics. The receiving side can use its own context to fetch the live object when a later operation genuinely needs one.
That refetch should happen inside the receiving actor or context owner. The main actor should usually consume presentation data, not acquire ownership of a background context. This prevents a common “fix” in which a background model is returned to the UI and then mutated from both sides.
Error and cancellation handling belong inside structured concurrency:
func refresh() async {
do {
let summary = try await store.insertSummary(
title: pendingTitle,
externalKey: pendingKey
)
await MainActor.run {
self.titleText = summary.title
self.recordID = summary.id
}
} catch is CancellationError {
// Preserve cancellation. Do not convert it into a save retry.
} catch {
await MainActor.run {
self.errorMessage = error.localizedDescription
}
}
}
The UI receives a result. It does not receive the actor’s context. Avoid DispatchSemaphore, synchronous queue hops, and detached tasks whose lifetime outlives the operation that created them. They can change the symptom while making cancellation and ownership harder to prove.
First week: migrate callers one boundary at a time
Once the first operation works, migration should follow the call graph rather than the file tree. Prioritize calls by write frequency, failure impact, and ownership ambiguity.
For each caller:
- Replace a model parameter with values or an identifier.
- Replace a model return with a DTO, identifier, or status result.
- Keep the old service behind the same protocol when possible.
- Change one observable boundary per commit.
- Add a test for cancellation and save failure.
- Record the old and new implementation paths.
- Keep a rollback switch until the new path passes the fixed-data run.
The old path should not become a second permanent architecture. It is a temporary control. A protocol-based seam or dependency-injected implementation is preferable to a global Boolean that can change during a live operation.
Audit temporary annotations after every migration:
@unchecked Sendable@preconcurrencyTask.detached- Broad
@MainActor - Synchronous locks or queue handoffs
- Escaping tasks without an explicit owner
Remove an annotation when the boundary no longer needs it. If one must remain, document the invariant, the module where it is allowed, the test that protects it, and the condition for removal.
A dependency that is not yet concurrency-safe should be contained at the module edge. Do not make business models broadly unchecked just because one adapter has not been updated. The Swift Evolution proposal on async function isolation provides useful background for understanding how isolation is inferred and transferred: SE-0461.
Before release: prove liveness and consistency in more than one environment
The migration is not ready to copy into every module when the compiler becomes quiet. The first path must pass three separate checks:
- Build correctness under the locked Swift 6.2 toolchain.
- Liveness under realistic cancellation and lifecycle changes.
- Data consistency after repeated writes and refetches.
Use a fixed dataset and exercise:
- Consecutive writes to the same logical records
- Cancellation during fetch and save
- App backgrounding and foregrounding
- Multiple windows or extensions accessing the store
- A task that fails halfway through an import
- Repeated launch and termination cycles
- A clean build and a build using the existing project cache
When a hang appears, save a thread sample and call stack. Check whether the main thread is blocked, whether an actor is awaiting another operation, whether a task has been cancelled, or whether two application-level waits form a cycle. Do not label the event a SwiftData deadlock solely because the UI stopped responding.
Validate in both the current delivery toolchain and the planned upgrade toolchain. The purpose is to separate source-level problems from DerivedData, simulator state, local package state, or one developer machine. A clean environment is especially important when an older branch and a refactored branch must be compared side by side. Teams can review ProxyMac's available Mac environment when a separate macOS workspace is needed for that comparison.
A useful rollback record contains:
- The commit where the new boundary was introduced
- The implementation selected by default
- The test dataset and launch conditions
- The compiler diagnostics before and after
- Thread samples for any hang
- The exact condition that permits returning to the old path
Only after the first operation passes this evidence gate should the same design be applied to another module.
Keep the migration operationally reversible
A staged code change still needs a staged environment. A technical lead may need the old branch, the refactored branch, and the planned toolchain available without contaminating one another with caches or simulator state.
The environment should make it possible to:
- Install or select the required Xcode version for the Swift 6.2 branch.
- Keep the upgraded toolchain separate from the delivery branch.
- Reproduce the same test project with the same input data.
- Capture build diagnostics and runtime samples.
- Reset the workspace without affecting another branch.
ProxyMac can be considered when the team needs a temporary Mac workspace for parallel branch validation rather than a permanent hardware purchase. The ProxyMac help resources are the appropriate place to verify environment access and operational details before assigning a migration task.
The trade-off is straightforward. A local Mac gives stable ownership and physical access, but it requires hardware availability, local setup, and cache discipline. A separate rented Mac can shorten environment preparation for temporary validation, but it is less suitable when a team needs long-term dedicated hardware, custom peripherals, or uninterrupted heavy workloads. The right choice depends on whether the task is a bounded migration check or an ongoing build fleet.
FAQ
Which SwiftData call chain should be migrated first?
Start with the write path that combines the highest failure risk with a clear owner. Imports, synchronization, and repeated background saves are usually better candidates than isolated reads. Trace one complete operation to ModelContext.save(), then move only that boundary. Keep the old implementation available until compilation, cancellation, liveness, and data consistency have been checked.
Should a @ModelActor return model objects or Sendable data?
Prefer PersistentIdentifier, immutable value types, or an explicitly Sendable DTO. A managed model object belongs to the context and isolation domain that owns it. Returning it across an actor boundary makes ownership unclear and can recreate the original problem. The receiving actor should refetch by identifier in its own context when it needs a live model.
How can background SwiftData writes avoid sending models back to the main actor?
Keep the write, save, and result calculation inside the @ModelActor. Return a small result such as an identifier, status value, or DTO. Let the main actor update presentation state from that result. Do not pass a background ModelContext or managed model into the UI, and do not use synchronous queues or semaphores to force a return.
Can an older project migrate only one target or data module?
Yes. Swift language mode and concurrency settings are selected by project and target configuration, so a staged migration can begin in a focused target or persistence module. Keep compatibility code at the module edge, document its exit condition, and avoid allowing @preconcurrency or unchecked sendability annotations to spread through shared models.
How should the old implementation remain available during the refactor?
Introduce a protocol or small service boundary, then provide the current implementation and the new actor-backed implementation behind it. Select the implementation through dependency injection or a controlled build setting. Preserve the same input and output contract, record which path was exercised, and remove the switch only after the new path passes fixed-data and cancellation tests.
A staged Swift 6.2 SwiftData concurrency refactor is usually a better fit than a global annotation when the project must keep shipping. The global @MainActor shortcut can move persistence work onto the UI executor, @unchecked Sendable can conceal ownership defects, and a single local machine can make environment differences look like source-level failures. A rented Mac from ProxyMac can provide a separate workspace for temporary branch and toolchain validation, while teams with permanent heavy workloads or physical-device requirements may still be better served by dedicated hardware. For environment access and account operations, the ProxyMac console is the next step after the code boundary and rollback path are defined.
FAQ
Further Reading
Run Your SwiftData Refactor on a Remote Mac
Rent a dedicated Mac from ProxyMac to build and test Swift 6.2 projects in a ready-to-use macOS environment.
Validate concurrency changes across clean macOS environments without replacing your local development setup.