skip to content

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%

answer

  1. compound key, not one property
  2. freestanding macros in the class body
  3. iOS 18 availability
  4. normalise the date first

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.

solid answer

~40 s

`@Attribute(.unique)` constrains one property, so a rule over a pair needs `#Unique`, a freestanding macro written inside the `@Model` class body: `#Unique<CheckIn>([\.habitName, \.day])`. Each array is one constraint, and you can pass several. A save that collides behaves like `.unique`: SwiftData updates the stored record instead of throwing. `#Index<CheckIn>([\.day], [\.habitName, \.day])` declares binary indexes for the queries you run; an overload takes `.binary` and `.rtree` index kinds. Uniqueness compares exact values, so store `Calendar.current.startOfDay(for:)` in `day`, not a timestamp. Both macros are iOS 18 API: with an iOS 17 deployment target the build fails with "'Unique' is only available in iOS 18 or newer", so you raise the target or annotate the model with `@available(iOS 18, *)`.

code

swift · 19 lines
swift
import Foundation
import SwiftData

@available(iOS 18, *)
@Model
final class CheckIn {
    #Unique<CheckIn>([\.habitName, \.day])
    #Index<CheckIn>([\.day], [\.habitName, \.day])

    var habitName: String
    var day: Date
    var note: String = ""

    init(habitName: String, on date: Date, note: String = "") {
        self.habitName = habitName
        self.day = Calendar.current.startOfDay(for: date)
        self.note = note
    }
}

go deeper

for a junior

Know that SwiftData has #Unique for compound rules and #Index for faster queries, and that both need iOS 18.

for a middle

Write #Unique with one array per constraint and #Index with the key paths your fetches use, inside the model body.

for a senior

Spot why a compound rule never fires, such as raw timestamps, and handle the iOS 18 availability against an iOS 17 deployment target.

for a principal

Weigh raising the deployment target to iOS 18 against gating models, and budget for indexes that slow every insert.

## Why @Attribute(.unique) is not enough SwiftData's `@Attribute(.unique)` makes **one** property unique across all records of a model. A habit tracker's rule is different: one `CheckIn` per habit **per day**. Neither `habitName` nor `day` is unique on its own; only the pair is. Putting `.unique` on both properties would be wrong twice over, because each would become unique separately, allowing only one check-in per habit ever and one check-in per day across all habits. ## Declaring a compound constraint with #Unique iOS 18 added `#Unique`, a **freestanding declaration macro** that you write inside the model's body, next to the properties: ```swift import Foundation import SwiftData @available(iOS 18, *) @Model final class CheckIn { #Unique<CheckIn>([\.habitName, \.day]) var habitName: String var day: Date init(habitName: String, day: Date) { self.habitName = habitName self.day = day } } ``` Its declaration is `macro Unique<T>(_ constraints: [PartialKeyPath<T>]...) where T: PersistentModel`, so: - each **array** is one constraint, and an array with several key paths is a **compound** constraint; - you can pass **several arrays**, as in Apple's example `#Unique<Person>([\.id], [\.givenName, \.familyName])`; - per Apple's documentation, a relationship can take part only when it references a **single** model, not an array of models. A collision behaves the way `.unique` does: in an in-memory test store, saving a second check-in with the same habit and day left one record carrying the second check-in's note. Nothing is thrown. The same test without any `#Index` behaved identically, so uniqueness does not depend on an index. ## Normalise the key before you rely on it Uniqueness compares stored values **exactly**. Check-ins at 08:00 and 09:00 on the same date are two different `Date` values, so the constraint never fires and both are kept. Store the start of the day instead, in the model's initializer: 1. Accept the moment of the check-in as an init parameter. 2. Assign `Calendar.current.startOfDay(for: date)` to `day`. 3. Decide which calendar and time zone define "a day" before you ship, because the stored key depends on that choice. ## Declaring indexes with #Index `#Index` is also an iOS 18 freestanding macro, with two forms: - `#Index<CheckIn>([\.day], [\.habitName, \.day])` declares **binary** indexes, one per array; this suits filtering and sorting by date and by habit-and-date. - `#Index<T>(_ indices: Schema.Index<T>.Types<T>...)` takes `.binary([...])` or `.rtree([...])` explicitly. In a test on macOS 27, an R-tree index over two `Double` properties crashed the app while the container was being created, with the exception "rtree indexes can only be created for floats or integers < 32 bit", so check the property types before choosing it. Index the key paths your fetches filter and sort on; every index also costs work on each insert and update. ## Checking what the macros declared You do not have to trust the macro text alone. The schema SwiftData builds is inspectable: - `Schema([CheckIn.self]).entities` returns the entity for the model. - The entity's `uniquenessConstraints` lists each constraint as key-path names; for the model above it printed `[["habitName", "day"]]`. - The entity's `indices` lists each index with its kind; it printed `[["binary", "day"], ["binary", "habitName", "day"]]`. A quick test with an in-memory container then shows the runtime behaviour: insert two check-ins with the same habit and day, save, and count the results. That test is also the cheapest way to catch the timestamp mistake described above before it ships. ## Availability and the iOS 17 baseline | Declaration | First iOS | Scope | |---|---|---| | `@Attribute(.unique)` | 17 | One property | | `#Unique` | 18 | One or more compound constraints | | `#Index` | 18 | Binary or R-tree indexes | With an iOS 17.0 deployment target, adding `#Unique` to an ungated model fails the build with "'Unique' is only available in iOS 18 or newer". The usual choices are raising the deployment target to iOS 18, or annotating the model class with `@available(iOS 18, *)` and only registering it with the container on iOS 18. Adding a uniqueness rule to a store that already holds duplicate rows is a data fix that belongs to the lesson on schema migrations.

  • Does SwiftData's #Unique need a matching #Index before it is enforced?
    No. In a test store, `#Unique<CheckIn>([\.habitName, \.day])` with no `#Index` still turned a second save of the same pair into an update of the stored check-in. Add `#Index` for the fetches you run, such as filtering by day, not to switch uniqueness on.
  • Why store the start of the day in a SwiftData CheckIn's day property instead of the check-in time?
    Because the unique constraint compares stored values exactly. Two check-ins at different times on the same date are different `Date` values, so both are kept and the rule never fires. Normalise with `Calendar.current.startOfDay(for:)` in the initializer, and settle which time zone defines a day before the first release.
  • Can a SwiftData #Unique constraint include a relationship key path?
    Only when the relationship references a single model, according to Apple's documentation for the macro. A to-many relationship, an array of models, cannot take part in a unique constraint.

  • Putting @Attribute(.unique) on habitName and day makes the pair unique.
  • #Unique runs on iOS 17 devices if the app builds with the iOS 27 SDK.
  • A #Unique violation makes save() throw an error.
  • #Unique is only enforced when an #Index covers the same key paths.
  • Storing full timestamps in day still gives one check-in per day.

Assumes the iOS 27 SDK; #Unique and #Index were added in iOS 18, so an app that still deploys to iOS 17 must raise its target or gate the model.