100 Days of SwiftUI

Day 54

2026-06-27

Project 11, part 2

Designing good data structures is critically important

Creating books with SwiftData

  • create a data model
    • make sure to import SwiftData
    • use @Model for a class
    • the class needs to be initialized @Model requires an initializer be provided for 'Book' (from macro 'Model')
    • XCode completion is your friend here
  • ask SwiftData to create a model container
    • go to the App file and add the modifier .modelContainer(for: Book.self) to WindowGroup
    • don’t forget to import SwiftData
  • make a form that can create new entries
    • use @Environment property to get access to the model context
    • still need @State local properties to store the data while working with it
samoyed sketchsamoyed sketch

Adding a custom star rating component

  • design for flexibility (maybe reuse in a later project?) — which isn’t exactly YAGNI but learning more is better.
  • need to use @Binding
  • the #Preview won’t build unless you give it some data
  • .buttonStyle(.plain) makes it possible to tap individual stars (rather than have a single tap select all 5)
Also, having a library of UI components can’t be all bad

Building a list with @Query

  • SwiftData automatically makes items Identifiable so you don’t need to add id:... to your ForEach loop