Data Persistence with SwiftData

Mar 19 2025 · Swift 5.10, iOS 17, ipadOS 17, macOS 15, visionOS 1.2, Xcode 15

Lesson 05: SwiftData, Migrations & Working with Core Data

From Core Data to SwiftData Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Moving From Core Data to SwiftData

In the Starter folder, you’ll find another app called CoreData_SwiftUI. This a simple SwiftUI app that uses Core Data as the persistence framework. You’ll convert this app to use **SwiftData** with the knowledge you’ve gained in this course.

import Foundation
import SwiftData

class UserInfoModel {
  var firstName: String?
  var lastName: String?
  var gender: String?

}
init(
  firstName: String? = nil,
  lastName: String? = nil,
  gender: String? = nil
) {
  self.firstName = firstName
  self.lastName = lastName
  self.gender = gender
}
import Foundation
import SwiftData

@Model
class UserInfoModel {
  var firstName: String?
  var lastName: String?
  var gender: String?

  init(
    firstName: String? = nil,
    lastName: String? = nil,
    gender: String? = nil
  ) {
    self.firstName = firstName
    self.lastName = lastName
    self.gender = gender
  }
}
extension UserInfoModel {
  @MainActor
  static var preview: ModelContainer {
    do {
      let container = try ModelContainer(for: UserInfoModel.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true))

      let user1 = UserInfoModel(
        firstName: "Taylor",
        lastName: "SwiftData",
        gender: "Female"
      )
      let user2 = UserInfoModel(
        firstName: "Joe",
        lastName: "Smith",
        gender: "Male"
      )
      let user3 = UserInfoModel(
        firstName: "Jane",
        lastName: "Doe",
        gender: "Female"
      )

      container.mainContext.insert(user1)
      container.mainContext.insert(user2)
      container.mainContext.insert(user3)

      return container
    } catch {
      print("Fatal Error: Could not create preview modelContainer.")
      // Return an empty or default ModelContainer
      do {
        return try ModelContainer(for: UserInfoModel.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true))
      } catch {
        fatalError("Failed to create fallback ModelContainer.")
      }
    }
  }
}
@main
struct CoreData_SwiftUIApp: App {
 // 1. delete the persistenceController
 let persistenceController = PersistenceController.shared

 var body: some Scene {
  WindowGroup {
    UserListView()
      // 2. delete the environment
      .environment(
        \.managedObjectContext,
          persistenceController.container.viewContext
      )
  }
 }
}

UserListView()
  .modelContainer(for: [UserInfoModel.self])
@Environment(\.modelContext) private var modelContext
@Query(
  sort: \UserInfoModel.firstName,
  order: .forward
) var users: [UserInfoModel]
.modelContainer(UserInfoModel.preview)
// Update the environment managedObjectContext to this
@Environment(\.modelContext) private var modelContext
/* Replace the current addItem code
let newItem = UserInfo(context: modelContext)
newItem.firstName = firstName
newItem.lastName = lastName
newItem.gender = gender

// remove the do-catch block
*/

let newUser = UserInfoModel(
  firstName: firstName,
  lastName: lastName,
  gender: gender
)
modelContext.insert(newUser)
dismiss()
.sheet(isPresented: $showingAddUser) {
  UserInfoView()
}
CoreData_SwiftUI.sqlite
CoreData_SwiftUI.sqlite-shm
CoreData_SwiftUI.sqlite-wal
var container: ModelContainer
init() {
  do {
    let storeURL = URL.applicationSupportDirectory.appending(
      path: "CoreData_SwiftUI.sqlite"
    )
    let config = ModelConfiguration(url: storeURL)
    container = try ModelContainer(
      for: UserInfoModel.self,
      configurations: config
    )
  } catch {
    fatalError("Failed to configure SwiftData container.")
  }
}
print(URL.applicationSupportDirectory.path(percentEncoded: false))
See forum comments
Cinema mode Download course materials from Github
Previous: SwiftData Migrations Demo Next: Migrations & Working with Core Data Conclusion