Dunfey · Hotel WWDC as data, est. 1983
Front desk everything
Years
Topics

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 ↗

Transcript all transcripts

Chapters

Code shown on screen · 9 snippets

Defining a SwiftData model swift · at 3:33 ↗
@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 swift · at 4:25 ↗
@Bindable var card: Card
Query models from SwiftData storage swift · at 5:52 ↗
@Query private var cards: [Card]
Setting up a model container for the window group swift · at 8:27 ↗
WindowGroup {
    ContentView()
}
.modelContainer(for: Card.self)
Providing a preview with sample data swift · at 9:24 ↗
#Preview {
    ContentView()
        .frame(minWidth: 500, minHeight: 500)
        .modelContainer(previewContainer)
}
Accessing the model context of the ContentView swift · at 10:30 ↗
@Environment(\.modelContext) private var modelContext
Insert a new model in the context swift · at 10:51 ↗
let newCard = Card(front: "Sample Front", back: "Sample Back")
modelContext.insert(object: newCard)
Start document-based application setup swift · at 13:34 ↗
@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 swift · at 16:51 ↗
@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