-
Meet SwiftData
SwiftData is a powerful and expressive persistence framework built for Swift. We'll show you how you can model your data directly from Swift code, use SwiftData to work with your models, and integrate with SwiftUI.
Chapitres
- 0:00 - Intro
- 1:07 - Using the model macro
- 3:17 - Working with your data
- 7:02 - Use SwiftData with SwiftUI
- 8:10 - Wrap-up
Ressources
Vidéos connexes
WWDC23
-
Rechercher dans cette vidéo…
-
-
1:27 - Adding @Model to Trip
import SwiftData @Model class Trip { var name: String var destination: String var endDate: Date var startDate: Date var bucketList: [BucketListItem]? = [] var livingAccommodation: LivingAccommodation? } -
2:46 - Providing options for @Attribute and @Relationship
@Model class Trip { @Attribute(.unique) var name: String var destination: String var endDate: Date var startDate: Date @Relationship(.cascade) var bucketList: [BucketListItem]? = [] var livingAccommodation: LivingAccommodation? } -
3:43 - Initialize a ModelContainer
// Initialize with only a schema let container = try ModelContainer([Trip.self, LivingAccommodation.self]) // Initialize with configurations let container = try ModelContainer( for: [Trip.self, LivingAccommodation.self], configurations: ModelConfiguration(url: URL("path")) ) -
3:58 - Creating a model container in SwiftUI
import SwiftUI @main struct TripsApp: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer( for: [Trip.self, LivingAccommodation.self] ) } } -
4:20 - Accessing the environment's ModelContext
import SwiftUI struct ContextView : View { @Environment(\.modelContext) private var context } -
5:13 - Building a predicate
let today = Date() let tripPredicate = #Predicate<Trip> { $0.destination == "New York" && $0.name.contains("birthday") && $0.startDate > today } -
5:32 - Fetching with a FetchDescriptor
let descriptor = FetchDescriptor<Trip>(predicate: tripPredicate) let trips = try context.fetch(descriptor) -
5:46 - Fetching with fetch and sort descriptors
let descriptor = FetchDescriptor<Trip>( sortBy: SortDescriptor(\Trip.name), predicate: tripPredicate ) let trips = try context.fetch(descriptor) -
6:15 - Working with a ModelContext
var myTrip = Trip(name: "Birthday Trip", destination: "New York") // Insert a new trip context.insert(myTrip) // Delete an existing trip context.delete(myTrip) // Manually save changes to the context try context.save() -
7:38 - Using @Query in SwiftUI
import SwiftUI struct ContentView: View { @Query(sort: \.startDate, order: .reverse) var trips: [Trip] @Environment(\.modelContext) var modelContext var body: some View { NavigationStack() { List { ForEach(trips) { trip in // ... } } } } }
-