Learning Swift Data
Created | 2025-01-06T07:56:00Z |
Updated | 2025-01-11T17:23:20Z |
Type | Research |
Status | In Progress |
- ModelConfiguration - used to configure the data store, name, location etc.
- ModelContainer - is responsible for creating and managing the underlying SQLite database file and maintaining data synchronisation.
- ModelContext - tracks, in memory the model objects that have been created, modified or deleted. It will inform the ModelContainer about those objects so that any changes can be committed to the database.
Basic Data Model
import Foundation
import SwiftData
@Model
class ChildModel {
var name: String
init(name: String) {
self.name = name
}
}
Hierarchical Data Model
import Foundation
import SwiftData
@Model
class ParentModel {
var name: String
var details: String
var date: Date
@Relationship(deleteRule: .cascade) var children = [ChildModel]()
init(name: String = "", details: String = "", date: Date = .now) {
self.name = name
self.details = details
self.date = date
}
}
Application Reference to Data Model
import SwiftData
import SwiftUI
@main
struct AppName: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: ParentModel.self)
}
}
The modelContainer() modifier tells SwiftData that it should:
- Create the storage for our data model object, or load it if it was created previously.
- Use that storage for the data inside the window group.
Now add this new property to the ContentView struct:
@Query var datamodels: [DataModel]