Close Menu
  • Home
  • AI
  • Big Data
  • Cloud Computing
  • iOS Development
  • IoT
  • IT/ Cybersecurity
  • Tech
    • Nanotechnology
    • Green Technology
    • Apple
    • Software Development
    • Software Engineering

Subscribe to Updates

Get the latest technology news from Bigteetechhub about IT, Cybersecurity and Big Data.

    What's Hot

    Navigating the labyrinth of forks

    July 18, 2025

    OpenAI unveils ‘ChatGPT agent’ that gives ChatGPT its own computer to autonomously use your email and web apps, download and create files for you

    July 18, 2025

    Big milestone for the future of quantum computing.

    July 18, 2025
    Facebook X (Twitter) Instagram
    Facebook X (Twitter) Instagram
    Big Tee Tech Hub
    • Home
    • AI
    • Big Data
    • Cloud Computing
    • iOS Development
    • IoT
    • IT/ Cybersecurity
    • Tech
      • Nanotechnology
      • Green Technology
      • Apple
      • Software Development
      • Software Engineering
    Big Tee Tech Hub
    Home»iOS Development»Using SwiftData with Preview in SwiftUI
    iOS Development

    Using SwiftData with Preview in SwiftUI

    big tee tech hubBy big tee tech hubJune 16, 2025004 Mins Read
    Share Facebook Twitter Pinterest Copy Link LinkedIn Tumblr Email Telegram WhatsApp
    Follow Us
    Google News Flipboard
    Using SwiftData with Preview in SwiftUI
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link


    In the earlier tutorial, I have walked you through the basics of SwiftData, a new framework introduced in iOS 17 as a replacement for Core Data. If you have followed that tutorial, you should now be familiar with using SwiftData to save and manage data in a database. The built-in @Model macro and the @Query macro greatly simplify the process of defining data model and retrieving records from the database, making it extremely easy for developers to handle persistent data.

    The Preview feature in SwiftUI is highly valuable as it allows developers to instantly visualize the app’s user interface without the need to launch the simulator. However, using SwiftData with SwiftUI Preview requires some additional steps. In this tutorial, we will explore how to integrate SwiftData with SwiftUI Preview effectively.

    Note: If you haven’t read the SwiftData tutorial, I highly recommend checking it out first, as this tutorial references some of the materials covered in that tutorial.

    Revisiting the Data Model and SwiftData

    In the previous example, we have built a model class for ToDoItem like this:

    import Foundation
    import SwiftData
    
    @Model class ToDoItem: Identifiable {
        var id: UUID
        var name: String
        var isComplete: Bool
    
        init(id: UUID = UUID(), name: String = "", isComplete: Bool = false) {
            self.id = id
            self.name = name
            self.isComplete = isComplete
        }
    }

    SwiftData simplifies the process of defining a schema using code. You only need to mark the model class with the @Model macro. SwiftData will then automatically enable persistence for the data class.

    In order to drive the data operations (like update, insert, read, and delete), we also need to set up the model container. In the ToDoDemoAppApp.swift, we have attached the modelContainer modifier like below:

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

    This configuration is essentially all you need before starting to work with SwiftData.

    Preview with SwiftData and In-memory Container

    In the Todo app demo, we have a ContentView that loads and displays the to-do item in the list view. Here is the sample code:

    struct ContentView: View {
        @Environment(\.modelContext) private var modelContext
    
        @Query var todoItems: [ToDoItem]
    
        var body: some View {
            NavigationStack {
                List {
                    ForEach(todoItems) { todoItem in
                        HStack {
                            Text(todoItem.name)
    
                            Spacer()
    
                            if todoItem.isComplete {
                                Image(systemName: "checkmark")
                            }
                        }
                    }
                }
    
                .navigationTitle("To Do List")
            }
        }
        }

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

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

    However, in this case, the preview only displays an empty Todo list because the container doesn’t have any data populated. If you desire to have some sample data, you can create a custom model container specifically for the preview. Here is an example:

    @MainActor
    let previewContainer: ModelContainer = {
        do {
            let container = try ModelContainer(for: ToDoItem.self,
                                               configurations: .init(isStoredInMemoryOnly: true))
    
            for _ in 1...10 {
                container.mainContext.insert(generateRandomTodoItem())
            }
    
            return container
        } catch {
            fatalError("Failed to create container")
        }
    }()
    
    func generateRandomTodoItem() -> ToDoItem {
        let tasks = [ "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 items. To use this preview container, you simply modify the preview code and specify to use the previewContainer:

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

    Once you made the modification, the preview pane should show you the Todo list view with 10 random items.

    swiftdata-preview-demo

    Summary

    SwiftUI Preview is a valuable feature that allows developers to visualize their app’s user interface instantly, without the need to launch the simulator. This tutorial provides comprehensive guidance on effectively using SwiftData with SwiftUI Preview. You should learn how to create a custom container populated with sample data specifically for preview purposes.

    If you enjoy reading this tutorial and want to learn more about SwiftUI, don’t forget to check out our Mastering SwiftUI book for iOS 17 and Xcode 15.



    Source link

    Preview SwiftData SwiftUI
    Follow on Google News Follow on Flipboard
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email Copy Link
    tonirufai
    big tee tech hub
    • Website

    Related Posts

    Deep dive into Swift frameworks

    July 17, 2025

    How to parse JSON in Swift using Codable protocol?

    July 16, 2025

    Four Months in the Making: SwiftMCP 1.0 is Here

    July 15, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Editors Picks

    Navigating the labyrinth of forks

    July 18, 2025

    OpenAI unveils ‘ChatGPT agent’ that gives ChatGPT its own computer to autonomously use your email and web apps, download and create files for you

    July 18, 2025

    Big milestone for the future of quantum computing.

    July 18, 2025

    Exploring supersymmetry through twisted bilayer materials – Physics World

    July 18, 2025
    Advertisement
    About Us
    About Us

    Welcome To big tee tech hub. Big tee tech hub is a Professional seo tools Platform. Here we will provide you only interesting content, which you will like very much. We’re dedicated to providing you the best of seo tools, with a focus on dependability and tools. We’re working to turn our passion for seo tools into a booming online website. We hope you enjoy our seo tools as much as we enjoy offering them to you.

    Don't Miss!

    Navigating the labyrinth of forks

    July 18, 2025

    OpenAI unveils ‘ChatGPT agent’ that gives ChatGPT its own computer to autonomously use your email and web apps, download and create files for you

    July 18, 2025

    Subscribe to Updates

    Get the latest technology news from Bigteetechhub about IT, Cybersecurity and Big Data.

      • About Us
      • Contact Us
      • Disclaimer
      • Privacy Policy
      • Terms and Conditions
      © 2025 bigteetechhub.All Right Reserved

      Type above and press Enter to search. Press Esc to cancel.