Instruction

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

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

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

Unlock now

SwiftData: Modernizing Data Persistence for SwiftUI

SwiftData, a Swift-native persistence framework, is designed exclusively with the Swift programming language. Tailored to seamlessly integrate with SwiftUI, it offers a streamlined and accelerated process for persisting user data within SwiftUI applications.

SwiftData Essentials: A Simple Walkthrough

Creating SwiftData Model

Defining the data model is a crucial first step when integrating SwiftData into your app. It uses tools like macros and property wrappers to easily persist and retrieve your data models. To enable the storage of instances of a model class with SwiftData, import the SwiftData framework and mark the class with the @Model macro. This macro ensures that SwiftData is able to preserve and track all changes for this model by adding conformance to both PersistentModel and Observable protocols. Here’s an example of a normal class model converted into SwiftData model:

import SwiftData

@Model
class JokeAuthor: Identifiable {
  var id = UUID()
  var name: String
  var country: String

  init(id: UUID = UUID(), name: String = "", country: String = "") {
    self.id = id
    self.name = name
    self.country = country
  }
}
@Attribute(.unique) var id = UUID()

Putting SwiftData Model into Use

You created your SwiftData model successfully. Now, you need to tell SwiftData to persist this model in runtime. To do this, you use the modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:) view modifier at the very top level of your view hierarchy, which is mostly your ContentView():

@main
struct AppMain: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
        .modelContainer(for: [JokeAuthor.self])
    }
  }
}

SwiftData CRUD Operations

Reading

Now that both your app and SwiftData recognize the model type for persistence throughout your app, you can access this model from any part of your app. To achieve this, add the Query property wrapper to a property with the same type as the one you added to your modelContainer.

@Query(sort: \JokeAuthor.country, order: .forward) var jokeAuthors: [JokeAuthor]

Creating

Initially, your model will have no data. To populate your model, you utilize an environment property wrapper offered by SwiftData called modelContext. The model context is responsible for managing in-memory model data and coordinating with the model container to ensure successful data persistence. Begin by specifying the context:

@Environment(\.modelContext) private var context
context.insert(newAuthor)

Updating

Updating data in SwiftData is a seamless process that doesn’t need direct interaction with the modelContext. By simply modifying the instances retrieved through the Query property wrapper, the data is automatically updated. In the provided example, the jokeAuthors array reflects the updated data, effortlessly handling the updating process of this model.

@Query(sort: \JokeAuthor.country, order: .forward) var jokeAuthors: [JokeAuthor]

Deleting

Deleting data in SwiftData follows a straightforward approach, similar to creating. Using the delete method, you can effortlessly remove instances from your model. In the given example, the author instance is passed to the delete method, triggering the removal of the corresponding data.

context.delete(author)
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo