2023 EssentialsSwiftUI & UI Frameworks
WWDC23 · 19 min · Essentials / SwiftUI & UI Frameworks
Build an app with SwiftData
Discover how SwiftData can help you persist data in your app. Code along with us as we bring SwiftData to a multi-platform SwiftUI app. Learn how to convert existing model classes into SwiftData models, set up the environment, reflect model layer changes in UI, and build document-based applications backed by SwiftData storage. To get the most out of this session, you should be familiar SwiftData. For an introduction, check out "Meet SwiftData" from WWDC23.
Watch at developer.apple.com ↗Chapters
Code shown on screen · 9 snippets
Defining a SwiftData model
final class Card {
var front: String
var back: String
var creationDate: Date
init(front: String, back: String, creationDate: Date = .now) {
self.front = front
self.back = back
self.creationDate = creationDate
}
} Binding to a SwiftData model
var card: Card Query models from SwiftData storage
private var cards: [Card] Setting up a model container for the window group
WindowGroup {
ContentView()
}
.modelContainer(for: Card.self) Providing a preview with sample data
#Preview {
ContentView()
.frame(minWidth: 500, minHeight: 500)
.modelContainer(previewContainer)
} Accessing the model context of the ContentView
(\.modelContext) private var modelContext Insert a new model in the context
let newCard = Card(front: "Sample Front", back: "Sample Back")
modelContext.insert(object: newCard) Start document-based application setup
@main
struct SwiftDataFlashCardSample: App {
var body: some Scene {
#if os(iOS) || os(macOS)
DocumentGroup(editing: Card.self, contentType: <#UTType#>) {
<#code#>
}
#else
WindowGroup {
ContentView()
.modelContainer(for: Card.self)
}
#endif
}
} Finish document-based application setup
@main
struct SwiftDataFlashCardSample: App {
var body: some Scene {
#if os(iOS) || os(macOS)
DocumentGroup(editing: Card.self, contentType: .flashCards) {
ContentView()
}
#else
WindowGroup {
ContentView()
.modelContainer(for: Card.self)
}
#endif
}
} Resources
Related sessions
-
34 min -
13 min -
9 min -
11 min -
9 min -
16 min