SwiftData makes it easy to persist data using declarative code. You can query and filter data using regular Swift code. And it’s designed to integrate seamlessly with SwiftUI.
Related docs:
Preserving #
Model #
@Model
import SwiftData
@Model
class Trip {
var name: String
var destination: String
var startDate: Date
var endDate: Date
var accommodation: Accommodation?
}
Customize persistence behavior #
@Attribute
@Attribute(.unique) var name: String
@Relationship
@Relationship(.cascade) var accommodation: Accommodation?
@Transient
temporary data that doesn’t need saving.
@Transient var destinationWeather = Weather.current()
Configure Container #
ModelContainer
ModelConfiguration
Save Model for later use #
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var context
}
Query to display #
@Query