Data Persistence in SwiftUI

Jun 20 2024 · Swift 5.9, iOS 17.2, Xcode 15.1

Lesson 03: Persisting Data with 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

Open the starter project for this lesson; you’ll find the familiar JoyJotter app from the previous lessons. However, take a moment to notice a new addition: the Jokes Authors tab. Here, you’ll discover a list of authors along with their corresponding countries. Dive into the details by selecting an author, where you can seamlessly edit their name or country and save your changes. This model will be the main focus of your adventure as you use SwiftData to save and work with it. It’s time to start your journey to improve the JoyJotter app with SwiftData.

Configuring SwiftData Model

Open JokeAuthorModel. You’ll find the JokeAuthor model. Import the SwiftData library to this file; then, you’ll convert this model to a SwiftData model by adding the @Model macro. Then, add the @Attribute(.unique) property wrapper to the id property to make it unique all over the instances of this model.

@Model
class JokeAuthor: Identifiable {
  @Attribute(.unique) 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
  }
}
let modelContainer: ModelContainer

init() {
  do {
    modelContainer = try ModelContainer(for: JokeAuthor.self)
  } catch {
    fatalError("Could not initialize ModelContainer")
  }
}
.modelContainer(for: modelContainer)

SwiftData CRUD Operations

Reading

Open JokeAuthorsListView, and import the SwiftData library to it. Then, replace the jokeAuthors property with the one provided with the Query property wrapper. You can sort it according to country and sort it ascending using the parameters of the Query property wrapper.

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

Creating

Open AddAuthorView. It’s the view responsible for adding new jokes. Import the SwiftData library into it, then add the context environment property to it. This one will help you create new instances of your model, as you learned in the previous section.

@Environment(\.modelContext) private var context

Updating

Open EditAuthorView. Remove the authorName, authorCountry, and jokeAuthors properties. Replace selectedAuthor property with new Bindable author property. You’ll pass the author to be edited from the JokeAuthorsListView to this property.

@Bindable var author: JokeAuthor
TextField("Author Name", text: $author.name)
TextField("Country", text: $author.country)
presentationMode.wrappedValue.dismiss()
EditAuthorView(
  author: author
)

Deleting

The final CRUD operation that you’ll add to your model is the deleting part. Open JokeAuthorsListView. Then add the context environment property to it.

@Environment(\.modelContext) private var context
for index in indexSet {
  let author = jokeAuthors[index]
  context.delete(author)
}
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion