how to use swift models

Asked on 08/03/2024

1 search

To use Swift models with SwiftData, you can follow these steps:

  1. Import the Framework: First, ensure you import the SwiftData framework into your project.

  2. Define Your Model: Use the @Model macro to define your data models. This macro helps in persisting your app's information with a lightweight API that feels natural in Swift.

    import SwiftData
    
    @Model
    class Trip {
        var destination: String
        var date: Date
        var notes: String?
        
        init(destination: String, date: Date, notes: String? = nil) {
            self.destination = destination
            self.date = date
            self.notes = notes
        }
    }
    
  3. Customize the Schema: You can further refine your model using attributes to specify behaviors on properties and relationships to describe how models relate to one another. For example, you can use the @Attribute macro to define unique constraints or indexing.

    @Model
    class Trip {
        @Attribute(.unique) var destination: String
        var date: Date
        var notes: String?
        
        init(destination: String, date: Date, notes: String? = nil) {
            self.destination = destination
            self.date = date
            self.notes = notes
        }
    }
    
  4. Model Container: Use the modelContainer modifier on your WindowGroup to tell the entire view hierarchy about your model.

    @main
    struct TripsApp: App {
        var body: some Scene {
            WindowGroup {
                ContentView()
                    .modelContainer(for: Trip.self)
            }
        }
    }
    
  5. Querying Data: You can fetch and query your models from the model container. This allows your views to populate with data from the model container.

    struct ContentView: View {
        @Query var trips: [Trip]
        
        var body: some View {
            List(trips) { trip in
                Text(trip.destination)
            }
        }
    }
    

For more detailed information, you can refer to the session "What’s new in SwiftData" which covers the adoption of SwiftData, customizing the schema, and other new features like indexing and unique constraints.

Relevant Sessions