skip to content

@Model & Schema Macros

The @Model macro turns a Swift class into a persisted model, with @Attribute and @Transient refining storage. Interviewers treat it as a Core Data comparison: what the macro generates for you.

on this pageshow

explore

questions

5

In SwiftData, what does marking a class with the @Model macro give you, and why must a model be a class rather than a struct?

level: juniorimportance: must knowfreq 75%

answer

  1. two conformances from one macro
  2. stored properties become accessors
  3. computed properties stay out
  4. class-only protocol, one instance per record

basics

~20 s

@Model makes a class persistable: it adds PersistentModel and Observable conformance and rewrites each stored property to read and write SwiftData's backing data. It must be a class because PersistentModel is class-only and a context tracks each instance by identity.

solid answer

~50 s

Annotating a class with `@Model` is how SwiftData learns your schema: the Swift class is the source of truth, with no separate model file. At build time the macro adds `PersistentModel` and `Observable` conformance, adds members such as `persistentBackingData`, `schemaMetadata` and `init(backingData:)`, and turns every stored property into accessors that go through the model's backing data and report reads and writes to Observation. By default every non-computed property of a supported type is persisted: `String`, `Int`, `Bool`, `Date`, `Data`, and `Codable` structs and enums. Computed properties are not. A model has to be a class because `PersistentModel` refines `AnyObject`: a `ModelContext` hands out one shared instance per record and tracks edits made to it, which a copied value cannot give. `@Model struct Habit` fails to compile with "'@Model' cannot be applied to struct type 'Habit'".

code

swift · 20 lines
swift
import Foundation
import SwiftData

enum Cadence: String, Codable {
    case daily, weekly
}

@Model
final class Habit {
    var name: String
    var cadence: Cadence
    var createdAt: Date
    var isWeekly: Bool { cadence == .weekly }

    init(name: String, cadence: Cadence = .daily) {
        self.name = name
        self.cadence = cadence
        self.createdAt = .now
    }
}

go deeper

for a junior

Recall that @Model goes on a class, that every stored property of a supported type is saved, and that computed properties are not.

for a middle

Explain what the macro generates: PersistentModel and Observable conformance, backing data, schema metadata, init(backingData:) and accessor-rewritten properties.

for a senior

Show you can read the expansion when it breaks: why let properties and non-Codable types fail, and why a model object is not Sendable.

for a principal

Treat the @Model classes as the schema contract: a changed property is a store change, so model edits deserve the review an API change gets.

## What @Model is for SwiftData is Apple's Swift-native persistence framework, and `@Model` is the macro that turns an ordinary Swift class into a **persistent model**: a type whose instances SwiftData can insert, save, fetch and delete. Apple's documentation describes the class itself as the source of truth for your app's model layer. There is no model editor file to keep in sync; where Core Data describes entities in a separate managed object model, SwiftData reads the schema from the annotated classes. The macro shipped with iOS 17, the baseline for SwiftData. Marking the class is only half of the job. A model becomes persistent once a `ModelContext` inserts it and the context saves, and the container that holds the store must list the model types; both are covered in the lesson on containers and contexts. ## What the macro generates `@Model` is an attached macro, so you can read exactly what it adds by expanding it. For a class with one stored property, the expansion in the iOS 27 SDK contains: - **Extensions** that conform the class to `PersistentModel` and `Observable`. - A private `_$backingData` and the public `persistentBackingData` property, the object that actually holds the attribute values. - `schemaMetadata`, a list with one entry per persisted property, which SwiftData uses to build its internal schema. - `init(backingData:)`, the initializer SwiftData calls when it materializes an instance from a fetch. - An `ObservationRegistrar` plus `access(keyPath:)` and `withMutation(keyPath:_:)` helpers. - For **every persisted stored property**, generated accessors: the getter records the read with the registrar and calls `getValue(forKey:)`; the setter wraps `setValue(forKey:to:)` in `withMutation`. - A `Sendable` conformance marked unavailable, with a message pointing to a model actor or the model's `persistentModelID` instead; passing models across actors belongs to the lesson on contexts. Because `PersistentModel` refines `Observable`, `Hashable` and `Identifiable`, every model also gets an `id` (its `PersistentIdentifier`), equality and hashing, and SwiftUI can observe it without `ObservableObject` or `@Published`. ## Which properties become attributes | Declaration in a `@Model` class | Persisted? | Why | |---|---|---| | `var name: String` | Yes | Primitive type | | `var cadence: Cadence` (a `Codable` enum) | Yes | Codable value types are supported | | `var reminder: Reminder?` (a `Codable` struct) | Yes | Stored as a composite value of the model | | `var isWeekly: Bool { cadence == .weekly }` | No | Computed properties are transient by default | | `@Transient var cachedStreak = 0` | No | Explicitly excluded | | `let createdAt: Date` | Rejected | The macro cannot add accessors to a `let` | A property whose type is another `@Model` class is persisted too, as a relationship; delete rules and inverses are covered in the lesson on SwiftData relationships. ## Why a class and not a struct The compiler answers this for you. Applying `@Model` to a struct produces several errors at once, and each one points at a reason: 1. `'@Model' cannot be applied to struct type` — the macro itself refuses. 2. `non-class type 'Habit' cannot conform to class protocol 'PersistentModel'` — the protocol refines `AnyObject`. 3. `class properties are only allowed within classes` — the generated `schemaMetadata` is a `class var`. 4. `'required' initializer in non-class type` — the generated `init(backingData:)` is required. The design reason behind them is **identity**. A context keeps one live instance per stored record. When a list row and an edit form both hold the same `Habit`, they hold the same object, so an edit made in one place is the edit the context saves and the change every observer sees. A struct would be copied on every assignment, and the copies would drift apart from the record they came from. ## What you still write yourself The macro generates the persistence plumbing, not the model's design. You still: - write a designated `init` that assigns every stored property without a default, exactly as for any Swift class; SwiftData calls the generated `init(backingData:)`, not yours, when it materializes fetched instances; - choose property types SwiftData can store, and make your own structs and enums `Codable`; - refine individual properties with `@Attribute` or `@Transient` where the default does not fit; - tell the container which model types to manage, which the lesson on containers covers. Since iOS 26 a `@Model` class can also subclass another `@Model` class; the macro then requires an explicit availability annotation such as `@available(iOS 26, *)` on the subclass. ## Mistakes interviewers listen for - Expecting `@Model` to write anything to disk by itself; it declares a schema, and a context inserts and saves. - Adding `ObservableObject` or `@Published` to a model; the macro already supplies Observation. - Assuming computed properties are saved. - Declaring persisted properties with `let`. - Storing a custom struct that is not `Codable`, which fails inside the generated accessors.

  • Why does a SwiftUI view update when a fetched @Model object changes, with no ObservableObject or @Published in sight?
    Because `@Model` also adds `Observable` conformance. Each generated getter records the read with the model's observation registrar, and each setter wraps the write in `withMutation`. SwiftUI tracks those reads while it evaluates `body` and invalidates the view when a property it read changes. Combine's `ObservableObject` is not involved.
  • How does declaring a model with @Model differ from Core Data's approach?
    With `@Model` the Swift class is the schema: the macro adds `PersistentModel` conformance, which SwiftData uses to examine the class and generate its internal schema at runtime. There is no model editor file and no `@NSManaged` property to keep in step with it, which is why renames and type changes show up in code review as ordinary Swift diffs.
  • Does @Model add a Codable conformance to the class so SwiftData can encode it?
    No. The macro adds `PersistentModel` and `Observable`, and through `PersistentModel` the class also becomes `Hashable` and `Identifiable`. SwiftData reads and writes each property through the generated backing-data accessors, not through `Codable`. `Codable` matters for the value types you store inside a model, such as a struct or enum property.

  • @Model works on a struct as long as its properties are Codable.
  • A model still needs ObservableObject and @Published for SwiftUI to see changes.
  • Computed properties on a @Model class are saved like stored ones.
  • Creating a @Model object writes it to disk straight away.
  • A @Model class needs a separate model file describing its entities.
open as a page

In SwiftData, what do @Attribute(.unique) and @Attribute(.externalStorage) change about how a habit's name and photo are stored?

level: middleimportance: must knowfreq 62%

basics

~20 s

@Attribute(.unique) makes the name unique across all Habit records, and saving a duplicate updates the stored record instead of throwing. @Attribute(.externalStorage) asks SwiftData to keep the photo's bytes in a separate file beside the store rather than inside the database.

open as a page

In a SwiftData @Model class, when do you mark a property @Transient instead of making it computed, and how does SwiftData treat it?

level: middleimportance: should knowfreq 48%

basics

~20 s

Use @Transient for stored state that must not be saved, such as a cached streak; computed properties are never saved anyway. It needs a default unless optional, stays out of the schema, and a freshly fetched instance starts at that default.

open as a page

After adding a property of a custom struct type, a SwiftData @Model class fails with "no exact matches in call to instance method 'getValue'"; why, and what fixes it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

@Model rewrites each stored property into accessors that call getValue(forKey:) and setValue(forKey:to:), whose overloads need a Codable value, a model or a model collection. A plain struct matches none; make it Codable, or use .transformable(by:) or @Transient.

open as a page

In SwiftData, a habit tracker must keep one CheckIn per habit per day and filter check-ins by date quickly; how do #Unique and #Index express that?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

Declare #Unique<CheckIn>([.habitName, .day]) and #Index<CheckIn>([.day]) inside the model; both arrived in iOS 18. A colliding save updates the stored check-in, and day must hold the start of the day, or every timestamp counts as unique.

open as a page