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

2023 Swift

WWDC23 · 11 min · Swift

Migrate to SwiftData

Discover how you can start using SwiftData in your apps. We’ll show you how to use Xcode to generate model classes from your existing Core Data object models, use SwiftData alongside your previous implementation, or even completely replace your existing solution. Before watching this session, make sure you check out "Meet SwiftData."

Watch at developer.apple.com ↗

Transcript all transcripts

Chapters

Code shown on screen · 6 snippets

Creating a ModelContainer in SwiftUI swift · at 4:37 ↗
@main
struct TripsApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(
            for: [Trip.self, BucketListItem.self, LivingAccommodation.self]
        )
    }
}
Object creation in Core Data swift · at 4:57 ↗
@Environment(\.managedObjectContext) private var viewContext

let newTrip = Trip(context: viewContext)
newTrip.name = name
newTrip.destination = destination
newTrip.startDate = startDate
newTrip.endDate = endDate
Object creation in SwiftData swift · at 5:30 ↗
@Environment(\.modelContext) private var modelContext

let trip = Trip(
    name: name, 
    destination: destination, 
    startDate: startDate, 
    endDate: endDate
)

modelContext.insert(object: trip)
Fetch with Query in SwiftData swift · at 6:16 ↗
@Query(sort: \.startDate, order: .forward)

var trips: [Trip]
Setting store path and enabling persistent history tracking in Core Data swift · at 7:30 ↗
let url = URL(fileURLWithPath: "/path/to/Trips.store")

if let description = container.persistentStoreDescriptions.first {
    description.url = url
    description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
}
Ensuring Core Data and SwiftData class names are unique swift · at 9:11 ↗
class CDTrip: NSManagedObject {
    // ...
}


@Model final class Trip {
    // ...
}

Resources