How to create or access a SwiftData Persistent Container in Swift

Code for a UIKit or AppKit application that enables you to access or create a SwiftData Persistent Container.

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 09/11/2023 at 15:34
Last Updated on 09/12/2023 at 16:15
<p>Three flowers that represent Swift, Swift Data and Xcode.  The text "Create a SwiftData Persistent Container" sits beneath them.</p>

Code for a UIKit or AppKit application that enables you to access or create a SwiftData Persistent Container.

SubscribeCheck out our SwiftData Quick Start Guide

To access or create a persistent container in SwiftData, use the code below.

Please remember to replace _SwiftDataModelName_ with the name of the SwiftData model that you wish that container to access. For multiple models, use a comma-separated convention i.e. [ModelA.self, ModelB.self, ModelC.self].

We recommend that you place it within a Singleton called DataCoordinator that acts as a MainActor.

We recommend placing this functionality within a Singleton that acts as a MainActor. If you do not use a MainActor, you will have to use Async/Await patterns.

How to create a singleton in SwiftHow to use async await in Swift projects

For more information on the Persistent Container and what you can do with it, check out the WWDC videos linked below.

Meet SwiftDataBuild an app with SwiftDataDive Deeper into SwiftData

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.

Consult our SwiftData Quick Start GuideSearch our Blog

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.
SubscribeContact UsVisit our BlogView our ServicesView our Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe