Update data in SwiftData – Swift

by
Ali Hasan
swift-concurrency swift-data swiftui-animation

The Problem:

A Swift developer is having trouble updating data in SwiftData. The documentation for the update method is not clear, and the developer is unsure how to use it. The developer’s code is failing with an exception of type NSException. The developer is looking for help understanding how to use the update method.

The Solutions:

Solution 1: Update data in SwiftData

SwiftData provides an intuitive way to update data without directly modifying the model context. Simply update the instance of the model you want to change, and the changes will be automatically propagated to the database.

Here’s a revised version of your code:

@State var teamScores = 0

func updateTeamScores() {
  counterModel.teamScores = teamScores 
}

In this example, we have a model called CounterModel with a property named teamScores. When the user updates the teamScores state variable, the framework will automatically update the corresponding CounterModel instance, persisting the changes to the database.

Remember to wrap the update operation within a withAnimation block to provide a smooth user experience during updates.

Solution 2: Binding using `@Bindable`

To update data in SwiftData, you can bind directly to an object via @Bindable. By making changes to the bound object, the changes will be saved/persisted automatically.

Here’s an example of how to use @Bindable to update data:

@Model
final class Item {
   @Bindable var text: String
}
struct EditorView: View {
   @Bindable var item: Item

   var body: some View {
      TextField("Item Text", text: $item.text)
   }
}

In this example, the `Item` is fetched via a @Query in the main view and passed on to the `EditorView`. When you change the value of `item.text` in the `EditorView`, the change will be automatically saved/persisted.

Q&A

How to update the data in SwiftData?

To update data in SwiftData, bind directly to an object via @Bindable and change the values you want.

How to add new data in SwiftData?

To add the data in SwiftData, use insert function in context.

Video Explanation:

The following video, titled "SwiftData! Updating a Simple ToDo List App (Ch. 5 BONUS ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

13:42. Go to channel · How To Preload Data Into SwiftData ModelContainer ⚡️ | SwiftData Tutorial | #5. tundsdev•2.8K views · 2:42:49. Go to ...