SwiftData (Introduced in iOS 17, WWDC 2023)
SwiftData is Apple's new declarative, Swift-native framework for handling persistence in applications. It simplifies the
complexities of Core Data while o@ering modern features that align better with Swift's paradigms.
Key Features:
• Swift-native: Designed with Swift conventions in mind, and integrates seamlessly with Swift Language features
like property wrappers and structured concurrency.
• Declarative syntax: Uses attributes (e.g., @Model) to declare database models. No need to manually define
managed object contexts and entity descriptions.
• Ease of use: Greatly simplified API and reduced boilerplate code compared to Core Data.
• Concurrency: Fully integrates with Swift's structured concurrency model, including async/await.
• Automatic persistence: Developers don't need to manually define fetch requests, save contexts, or handle
relationships; SwiftData manages this for you automatically.
• Integration with SwiftUI: Unified and greatly optimized for writing SwiftUI apps, allowing developers to integrate
persistence functionality e@ortlessly.
• Reduced configuration: No need to define models in an external .xcdatamodel file; everything is handled in
code.
TradeoRs:
• Newness: SwiftData is relatively new, so it may lack advanced features that Core Data provides. Additionally,
existing apps relying on Core Data would require migration to SwiftData.
• Limited backward compatibility: SwiftData is only available in iOS 17/macOS Sonoma and later. It cannot be
used in older versions of iOS/macOS.
• Smaller community: As it's new, SwiftData has a smaller user base, meaning fewer third-party tools or open-
source libraries supporting it.
Important definations:
macro Model() - Converts a Swift class into a stored model that’s managed by SwiftData
ModelContainer - An object that manages an app’s schema and model storage configuration.
ModelContext - An object that enables you to fetch, insert, and delete models, and save any
changes to disk.
macro Query() - Fetches all instances of the attached model type.