Swift Concurrency & Persistence (SwiftData, Core Data)
Structured concurrency with async/await, tasks and actors, the MainActor, and persisting models with SwiftData or Core Data.
Intermediate · about 10 hours · difficulty 4/5
Learn first: SwiftUI Data Flow & Composition, Async Code & the Main Thread
Modern iOS apps use Swift's built-in concurrency for networking and background work, and SwiftData (or Core Data in older code) for local persistence.
Swift concurrency
asyncfunctions andawaitcalls;URLSession.shared.data(from:)is async.- Structured concurrency:
async letandTaskGrouprun child tasks that are cancelled together. Task { }starts work from synchronous code; checkTask.isCancelledin long loops.- Actors protect mutable state from data races.
@MainActorguarantees code runs on the main thread; view models that drive UI are usually@MainActor. - Swift 6 strict concurrency checking turns many data races into compile errors. Expect
Sendablewarnings and learn to fix them rather than silence them.
SwiftData
Mark classes with @Model, attach a modelContainer to your app, query with @Query in views, and insert/delete via modelContext. Plan schema migrations with versioned schemas.
Core Data
Still common in existing apps: NSManagedObjectContext, fetch requests and background contexts. Learn to read it even if you start with SwiftData.
Pitfalls
Updating UI state from a background task without @MainActor causes warnings or crashes.
Good enough to move on: your app loads data concurrently, caches it in SwiftData and shows cached content offline.
Key concepts
- async/await and URLSession
- async let and TaskGroup
- Task cancellation
- Actors and @MainActor
- Sendable and strict concurrency
- SwiftData models and queries
- Core Data basics
- Combine awareness: Found in older codebases
Mini project
Build a podcast browser that fetches several feeds in parallel with a TaskGroup and persists episodes in SwiftData for offline viewing.
Check yourself
What does marking a view model with @MainActor guarantee, and why is that useful?
Free resources
- Swift concurrency (Swift.org)
- SwiftData (Apple)
- Core Data (Apple)