How to use SwiftData with a Singleton within a SwiftUI app

Oscar de la Hera Gomez
Three flowers that represent SwiftData, SwiftUI and XCode side by side. Beneath them sits the text "SwiftData in a SwiftUI Singleton."

To use SwiftData in a Singleton within a SwiftUI app, initialize the modelContext within the initializer. Then apply the container to views for seamless use.

This tutorial is based on our upcoming app Object Capture Pro, which uses a Singleton to manage all the SwiftData operations in a way that is interoperable with standard SwiftUI SwiftData actions and updates.

If you wish to be updated on the progress and release of this app, please subscribe using the link below.

Step One: Initialize the Singleton SwiftData Container

A screenshot of XCode showing the code for the initializer.

Add the ModelContainer to the Singleton, and within the init function set it.

Step Two: Apply Container to Views

A screenshot of XCode showing how to apply the container to a View.

To apply the modelContext to a view in a way that performs as expected, use code similar to the one below.

Please replace _SINGLETON_ with the name of your singleton class.

.modelContainer(SINGLETON.modelContainer)

Step Three: Use within a View

A screenshot of XCode showing how to use the container within a View.

Within a view, you can now use the model context as expected.

When changes are made, it will also update as expected.

To learn more about SwiftData within SwiftUI, consult the guide below.

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

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