20.7 C
Canberra
Friday, October 24, 2025

Utilizing SwiftData with Preview in SwiftUI


Within the earlier tutorial, I’ve walked you thru the fundamentals of SwiftData, a brand new framework launched in iOS 17 as a substitute for Core Information. When you have adopted that tutorial, it’s best to now be accustomed to utilizing SwiftData to avoid wasting and handle knowledge in a database. The built-in @Mannequin macro and the @Question macro tremendously simplify the method of defining knowledge mannequin and retrieving data from the database, making it extraordinarily straightforward for builders to deal with persistent knowledge.

The Preview function in SwiftUI is extremely beneficial because it permits builders to immediately visualize the app’s consumer interface with out the necessity to launch the simulator. Nevertheless, utilizing SwiftData with SwiftUI Preview requires some further steps. On this tutorial, we’ll discover how you can combine SwiftData with SwiftUI Preview successfully.

Be aware: When you haven’t learn the SwiftData tutorial, I extremely suggest checking it out first, as this tutorial references a number of the supplies lined in that tutorial.

Revisiting the Information Mannequin and SwiftData

Within the earlier instance, we’ve got constructed a mannequin class for ToDoItem like this:

import Basis
import SwiftData

@Mannequin class ToDoItem: Identifiable {
    var id: UUID
    var identify: String
    var isComplete: Bool

    init(id: UUID = UUID(), identify: String = "", isComplete: Bool = false) {
        self.id = id
        self.identify = identify
        self.isComplete = isComplete
    }
}

SwiftData simplifies the method of defining a schema utilizing code. You solely have to mark the mannequin class with the @Mannequin macro. SwiftData will then routinely allow persistence for the information class.

In an effort to drive the information operations (like replace, insert, learn, and delete), we additionally have to arrange the mannequin container. Within the ToDoDemoAppApp.swift, we’ve got connected the modelContainer modifier like beneath:

struct ToDoDemoAppApp: App {
    var physique: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(for: ToDoItem.self)
    }
}

This configuration is actually all you want earlier than beginning to work with SwiftData.

Preview with SwiftData and In-memory Container

Within the Todo app demo, we’ve got a ContentView that hundreds and shows the to-do merchandise within the record view. Right here is the pattern code:

struct ContentView: View {
    @Atmosphere(.modelContext) personal var modelContext

    @Question var todoItems: [ToDoItem]

    var physique: some View {
        NavigationStack {
            Checklist {
                ForEach(todoItems) { todoItem in
                    HStack {
                        Textual content(todoItem.identify)

                        Spacer()

                        if todoItem.isComplete {
                            Picture(systemName: "checkmark")
                        }
                    }
                }
            }

            .navigationTitle("To Do Checklist")
        }
    }
    }

You may make the preview work by writing the preview code like this:

#Preview {
    ContentView()
        .modelContainer(for: ToDoItem.self)
}

Nevertheless, on this case, the preview solely shows an empty Todo record as a result of the container doesn’t have any knowledge populated. When you need to have some pattern knowledge, you possibly can create a customized mannequin container particularly for the preview. Right here is an instance:

@MainActor
let previewContainer: ModelContainer = {
    do {
        let container = strive ModelContainer(for: ToDoItem.self,
                                           configurations: .init(isStoredInMemoryOnly: true))

        for _ in 1...10 {
            container.mainContext.insert(generateRandomTodoItem())
        }

        return container
    } catch {
        fatalError("Didn't create container")
    }
}()

func generateRandomTodoItem() -> ToDoItem {
    let duties = [ "Buy groceries", "Finish homework", "Go for a run", "Practice Yoga", "Read a book", "Write a blog post", "Clean the house", "Walk the dog", "Attend a meeting" ]

    let randomIndex = Int.random(in: 0..

We instantiate a ModelContainer with an in-memory configuration and populate the container with 10 random to-do gadgets. To make use of this preview container, you merely modify the preview code and specify to make use of the previewContainer:

#Preview {
    ContentView()
        .modelContainer(previewContainer)
}

When you made the modification, the preview pane ought to present you the Todo record view with 10 random gadgets.

swiftdata-preview-demo

Abstract

SwiftUI Preview is a beneficial function that enables builders to visualise their app’s consumer interface immediately, with out the necessity to launch the simulator. This tutorial gives complete steering on successfully utilizing SwiftData with SwiftUI Preview. It is best to learn to create a customized container populated with pattern knowledge particularly for preview functions.

When you get pleasure from studying this tutorial and need to study extra about SwiftUI, don’t neglect to take a look at our Mastering SwiftUI ebook for iOS 17 and Xcode 15.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles