SwiftDataPreviewer
is a lightweight Swift package designed to simplify SwiftUI previews using SwiftData. It provides an in-memory model container for use in DEBUG
builds, allowing you to preview your SwiftData-powered views with sample data.
- Seamless SwiftData Previews: Easily inject a
ModelContainer
into your SwiftUI previews. - In-Memory Storage: Prevents persistent data pollution while testing.
- Automatic Sample Data Insertion: Quickly preview lists and other data-driven views.
- Developer-Friendly API: Just wrap your view with
SwiftDataPreviewer
.
Add SwiftDataPreviewer
to your Swift project using Swift Package Manager.
dependencies: [
.package(url: "https://github.com/markbattistella/SwiftDataPreviewer", from: "1.0.0")
]
Alternatively, you can add SwiftDataPreviewer
using Xcode by navigating to File > Add Packages
and entering the package repository URL.
Note
SwiftDataPreviewer
is designed for SwiftUI previews only and is not meant for production usage. It provides an in-memory ModelContainer
that is automatically configured for SwiftData-powered views.
-
Define a SwiftData Model
Ensure your SwiftData model conforms to PersistentModel:
import SwiftData @Model class User { @Attribute(.unique) var id: UUID var name: String init(id: UUID = UUID(), name: String) { self.id = id self.name = name } }
-
Create a Preview Container
Define a PreviewContainer with the model types you want to include:
#if DEBUG import SwiftDataPreviewer let previewContainer = PreviewContainer([User.self]) #endif
-
Use
SwiftDataPreviewer
in Your PreviewsWrap your SwiftUI view in
SwiftDataPreviewer
and pass sample data:#if DEBUG import SwiftUI import SwiftData struct UserListView: View { @Query private var users: [User] var body: some View { List(users) { user in Text(user.name) } } } struct UserListView_Previews: PreviewProvider { static var previews: some View { SwiftDataPreviewer(preview: previewContainer, items: [ User(name: "Alice"), User(name: "Bob"), User(name: "Charlie") ]) { UserListView() } } } #endif
-
PreviewContainer creates an in-memory ModelContainer.
-
SwiftDataPreviewer injects the container into your SwiftUI view.
-
Sample data is automatically inserted so your previews are populated.
Contributions are welcome! If you find a bug or have suggestions for improvements, feel free to submit a pull request.
SwiftDataPreviewer
is available under the MIT licence. See the LICENCE file for more details.