Member-only story

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…

--

--

AppMakers.DEV — iOS App Development in SwiftUI and Swift
AppMakers.DEV — iOS App Development in SwiftUI and Swift

Published in AppMakers.DEV — iOS App Development in SwiftUI and Swift

Discover in-depth tutorials, resources, and guides on Swift, SwiftUI, and iOS app development. From building powerful apps to mastering the latest Swift techniques, AppMakers.Dev is your go-to destination for everything iOS development.

Alexander Adelmaer
Alexander Adelmaer

Written by Alexander Adelmaer

I write about iOS App Development at ✍️ https://medium.com/app-makers About Growth and Self-Development at ✍️ https://medium.com/take-action Join Me & My Blogs

No responses yet