Introduction
SwiftData is a new feature launched by Apple for persistent data storage. It allows us to create custom objects, define how they are linked together, retrieve them by filtering and sorting, and even sync them to iCloud.
Use SwiftData to not only fully enjoy the latest features of Swift, but it is also perfectly adapted to SwiftUI. If you use SwiftUI in your project, you will find that using SwiftData is very convenient.
The bottom layer of SwiftData is powered by a very mature Core Data. Core Data has been developed for nearly 20 years, and using it for underlying support allows us to enjoy many benefits. But SwiftData isn’t just a simple wrapper around Core Data: Apple has really gone all out to isolate and solve the key pain points for developers using the old framework, which means SwiftData will be useful to anyone who has used Core Data in the past. is a major improvement.
The catch: SwiftData only supports iOS 17 or higher, and corresponding versions of other platforms – namely macOS Sonoma, tvOS 17, watchOS 10, and VisionOS 1.0.
SwiftData is an excellent choice for any type of device storage, including:
- Persistent storage of user data, such as their to-do list or browsing history.
- Temporary storage of user data, where SwiftData is used as a cache for data fetched from the server.
- Document-based apps, such as text or video editors.
- Complex user settings or historical data.
It is not a good choice in the following situations:
- Need to support many users using iOS 16 and earlier. Although SwiftData and Core Data can coexist in the same application, this will require additional work.
- Data is only stored in CloudKit or other equivalent services, and real-time data is required at all times.
- Requires the full range of capabilities provided by Core Data. Many features of Core Data are not yet available in SwiftData, so if you have more advanced use cases, you should probably stick with Core Data.
Basic use
For SwiftUI, using SwiftData is still very simple. Suppose we have a class that represents a timestamp: Item. The code is as follows:
final class Item {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
We need the following steps to use SwiftData. First, import the framework and add @Model
the macro in front of the class:
import SwiftData
@Model
final class Item {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
In this way, the transformation of the model is completed. The next step is to use it. We need to configure it in the APP entry structure:
var sharedModelContainer: ModelContainer = {
let schema = Schema([
Item.self
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(sharedModelContainer)
}
We see that the above code mainly does two things:
- Configure ModelContainer. The purpose here is to tell the system that I want the data to persist Item.
- Use the modelContainer modifier to tell the system that the entire application will use the model.
In this way, we have completed the preparation for the persistence of the Item, and the next step is the specific addition, deletion, modification and check. Code example:
//
@Environment(\.modelContext) private var modelContext
//
private func addItem() {
let newItem = Item(timestamp: Date())
modelContext.insert(newItem)
}