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:

  1. Create a Sample Data Struct: Start by creating a new struct called SampleData that conforms to PreviewModifier. 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.

  2. 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.

  3. 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.

  4. 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.

  5. Extension to Preview Trait: Add an extension to PreviewTrait to easily access this sample data. This creates a new static property called sampleData which will apply this sample data structure as a modifier.

  6. 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.