How to update an object in SwiftData in Swift

Oscar de la Hera Gomez
Three flowers that represent Swift, Swift Data and Xcode.  The text "Update an Object in a SwiftData Persistent Container" sits beneath them.

A step by step guide on updating objects in a SwiftData persistent storage container using SwiftUI, UIKit or AppKit.

As mentioned in the videos linked below, updating SwiftData objects is as simple as updating the object's variables - SwiftData handles the rest.

A screenshot of an iPhone showing the result of the sample app available on our open source swift GitHub repository.

The following tutorial has been made available, along with a simple app for demonstrating SwiftData, through the tutorial/swift-data-basics branch on our Open Source Swift Starter Project.

Step One: Setup the Project

A screenshot of Xcode showing the sample functionality that adds a new SwiftData object to a persistent container. The code snippet is available below.

Follow the tutorial linked below to add SwiftData to your project, along with the ability to add objects.

Step Two: Add the Update Functionality

A screenshot of Xcode showing a series of functions that can be used to update SwiftData objects. The code snippet is found below.

Add functionality similar that below to the project to update the relevant variables for objects within a SwiftData persistent storage container.

We recommend adding this to a file called DataCoordinator+SwiftData.swift, where DataCoordinator is the name of the MainActor singleton that manages the SwiftData.

Please note that the code snippet found above uses a custom error that we created to track SwiftData errors. To learn how to create custom errors, consult the tutorial below.

Step Three: Test

A screenshot of an iPhone showing the result of the sample app available on our open source swift GitHub repository.

Add functionality to update SwiftData objects by calling the functions created in Step Two.

Then, run the app and test that it works.

Looking to learn more about things you can do with SwiftData, Swift or XCode ?

Consult our quick start guide or search our blog to find educational content on learning how to use SwiftData, Swift or XCode.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details