WWDC23 introduces a new persistence Framework called SwiftData
.
Note: All the code in this project and below was generated after selecting "SwiftData" as a Storage option.
.modelContainer(for: Item.self)
: sets the model container in the sceneSwiftData
: enables you to add persistence to your app quickly, with minimal code and no external dependencies@Model
: converts a Swift class into a stored model that’s managed by SwiftData@Query private var items: [Item]
: a property wrapper that fetches a set of models and keeps those models in sync with the underlying data@Environment(\.modelContext) private var modelContext
: theSwiftData
model context
- Create a new Xcode project using Xcode 15 Beta
- Select "SwiftData" as Storage
- Select to host in "CloudKit"
- After you've created your project the following files below will be populated with
SwiftData
boilerplate code. - Create some "items" from the demo app and relaunch the simulator or device to verity that the items are being persisted.
import SwiftUI
import SwiftData
@main
struct SwiftDataDemoApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: Item.self)
}
}
import Foundation
import SwiftData
@Model
final class Item {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var items: [Item]
var body: some View {
NavigationView {
List {
ForEach(items) { item in
NavigationLink {
Text("Item at \(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))")
} label: {
Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
}
}
.onDelete(perform: deleteItems)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
Text("Select an item")
}
}
private func addItem() {
withAnimation {
let newItem = Item(timestamp: Date())
modelContext.insert(newItem)
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(items[index])
}
}
}
}
#Preview {
ContentView()
.modelContainer(for: Item.self, inMemory: true)
}