how do I setup previews for swiftdata
Asked on 09/11/2024
1 search
To set up previews for SwiftData, you can follow these steps as outlined in the "What’s new in SwiftData" session at WWDC 2024:
-
Create a Sample Data Struct: Start by creating a new struct called
SampleData
that conforms toPreviewModifier
. This struct will have two functions: one for setting up a shared context for the preview and another to apply the shared context to a view. -
Model Container as Shared Context: For your previews, vend a model container as the shared context for the sample data. Since a preview doesn't need to store anything to disk, create a model configuration that stores data in memory only and set up the model container.
-
Load Sample Data: Call a method to create an assortment of sample data and save it into the model container. This data will be used in your previews.
-
Apply the Model Container: Implement a method to add this model container to whichever view the sample data is used for by applying the container using the
modelContainer
modifier. -
Extension to Preview Trait: Add an extension to
PreviewTrait
to easily access this sample data. This creates a new static property calledsampleData
which will apply this sample data structure as a modifier. -
Use in Previews: When declaring a preview for any of your SwiftUI views, use
sampleData
with the traits parameter. This will create an in-memory model container, load the sample data, and modify your previews to use it in its SwiftUI views.
For more detailed guidance, you can refer to the What’s new in SwiftData (06:41) session.

What’s new in Quick Look for visionOS
Explore how Quick Look in visionOS can elevate file preview and editing experiences in your app. We’ll cover the integration of in-app and windowed Quick Look, as well as a brand-new API that customizes the windowed Quick Look experience in your app. We’ll also share the latest enhancements to viewing 3D models within Quick Look.

Platforms State of the Union
Discover the newest advancements on Apple platforms.

What’s new in Xcode 16
Discover the latest productivity and performance improvements in Xcode 16. Learn about enhancements to code completion, diagnostics, and Xcode Previews. Find out more about updates in builds and explore improvements in debugging and Instruments.