SwiftUI SwiftData Quick Start Guide
A guide for helping you setup SwiftData with a SwiftUI project.
What is SwiftData?
Swift Data is a modern framework for on-device data storage, modelling and management intended to replace Core Data and provides a Swift-like API that integrates well with Swift UI.
Requirements
In order for your app to work with SwiftData you must:
- Have an iPhone, iPad or Mac running iOS17, iPadOS17 or MacOS13 or higher.
- Have an Mac running XCode 15 or higher.
- Have iOS17 installed on a Mac running Xcode 15 or higher.
Apple Developer Resources
We recommend that you consult all of WWDC's videos on Swift Data.
Seperately, we also recommend you consult our standard SwiftData Quick Start Guide and associated resources.
Guide
We offer an open source starter project which is based off our UIKit SwiftData Guide. This can be found at the link below at the tutorials/swiftdata/101 branch.
The key difference is that there is no DataCoordinator or Notifications and everything is done within SwiftUI views.
Additional changes include:
Environment ModelContainer
We used the .modelContainer modifier within the app to pass the model context to the SwiftUI views.
These use the @Environment(\.modelContext) property wrapper to access the model context within the SwiftUI Views.
As demonstrated by the CountScreen, these modelContainers persist across views.
@Query Macro for gathering all objects
Instead of gathering all the objects using the DataCoordinator, we now use the @Query macro to gather all the objects.
This query updates as changes are made to the objects.
Updating data directly within SwiftUI Views
By applying @Bindable property wrapper to the SwiftData model parameter in a SwiftUI View, you can update data within a SwiftUI View.
Inserting and Deleting Objects directly in SwiftUI Views
You can now insert and delete objects directly by using the @Environment(\.modelContext) property wrapper to gather the modelContext and using it with the associated functions.
Swift Previews
We adapted the code to work with Swift previews.
This also includes a way to preview mock items.
Looking to learn more about SwiftUI, Swift, SwiftData, Design and Technology?
Search our blog to learn more about Swift, SwiftUI, SwiftData, design and technology.