Getting Started with SwiftData
One common question in SwiftUI app development is how to work with Core Data to save data permanently in the built-in database. Despite Apple's ongoing efforts to simplify the APIs of Core Data, new comers often find the framework challenging to use. However, there is good news on the horizon. Apple will be releasing a new framework called SwiftData in iOS 17 to replace Core Data. SwiftData is designed to be much easier to use for data modelling and management, offering a more user-friendly approach.
First and foremost, it's important to note that the SwiftData framework should not be confused with a database. Built on top of Core Data, SwiftData is actually a framework designed to help developers manage and interact with data on a persistent store. While the default persistent store for iOS is typically the SQLite database, it's worth noting that persistent stores can take other forms as well. For example, Core Data can also be used to manage data in a local file, such as an XML file.
Regardless of whether you're using Core Data or the SwiftData framework, both tools serve to shield developers from the complexities of the underlying persistent store. Consider the SQLite database, for instance. With SwiftData, there's no need to worry about connecting to the database or understanding SQL in order to retrieve data records. Instead, developers can focus on working with APIs and Swift Macros, such as
@Model, to effectively manage data in their applications.
The SwiftData framework is newly introduced in iOS 17 to replace the previous framework called Core Data. Core Data has long been the data management APIs for iOS development since the era of Objective-C. Even though developers can integrate the framework into Swift projects, Core Data is not a native solution for both Swift and SwiftUI.
In iOS 17, Apple finally introduces a native framework called SwiftData for Swift on persistent data management and data modeling. It's built on top of Core Data but the APIs are completely redesigned to make the most out of Swift.
Using Code to Create the Data Model
If you have used Core Data before, you may remember that you have to create a data model (with a file extension .xcdatamodeld) using a data model editor for data persistence. With the release of SwiftData, you no longer need to do that. SwiftData streamlines the whole process with macros, another new Swift feature in iOS 17. Say, for example, you already define a model class for Song as follows:
To access the full content and the complete source code, please get your copy at https://www.appcoda.com/swiftui.