How to Use PreviewModifier to Display Sample SwiftData in SwiftUI

Learn How To Display Sample SwiftData in Preview In SwiftUI with PreviewModifier

In this guide, you’ll learn how to preview SwiftData models within SwiftUI using PreviewModifier. This step-by-step process walks you through setting up sample data, building a list view with SwiftData, and leveraging dynamic previews with @Previewable.

Step 1: Define Your Task Model in SwiftData

To start, we’ll define a SwiftData entity called Task. This model will store task details like title and completion status.

import Foundation
import SwiftData

@Model
class Task {
@Attribute(.unique) var id: UUID
var title: String?
var isCompleted: Bool

init(id: UUID = UUID(), title: String? = nil, isCompleted: Bool = false) {
self.id = id
self.title = title
self.isCompleted = isCompleted
}
}

Here, the Task class uses the @Model attribute, making it compatible with SwiftData. The properties include id, title, and isCompleted, where each task will have a unique ID.

Step 2: Build a Task List View with SwiftUI

Next, we’ll create a SwiftUI view to display our list of tasks. This view will include toggles to mark…

--

--