In SwiftData, what do @Attribute(.unique) and @Attribute(.externalStorage) change about how a habit's name and photo are stored?
answer
- a peer macro on one property
- duplicate insert, then save
- update instead of error
- large bytes beside the store
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.
solid answer
~40 s`@Attribute` is a peer macro that refines how SwiftData stores one property: `@Attribute(_ options:..., originalName:, hashModifier:)`. With `.unique`, no two records of the model may share the value, and the behaviour surprises people: when you insert a model whose unique value already exists and save, SwiftData updates the stored record with the new object's values instead of failing. That makes `.unique` on a stable server key a convenient import tool, and a trap if you expected an error. `.externalStorage` suits large `Data` such as a photo: the bytes go to a separate file next to the store instead of the database row. Other options include `.transformable(by:)` for a type that is not `Codable`, `.preserveValueOnDeletion`, `.spotlight` and `.allowsCloudEncryption`. A store synced through CloudKit cannot enforce `.unique`.
code
swift · 14 linesimport Foundation
import SwiftData
@Model
final class Habit {
@Attribute(.unique) var name: String
@Attribute(.externalStorage) var photo: Data?
var goal: Int = 1
init(name: String, goal: Int = 1) {
self.name = name
self.goal = goal
}
}go deeper
Know that @Attribute refines a single property and that .unique and .externalStorage are its most common options.
Explain that a duplicate .unique value updates the stored record on save, and where .externalStorage puts the bytes.
Judge when upsert-on-collision is a feature for imports and when it silently loses data, and spot options that a synced store cannot honour.
Decide which natural keys a team may mark unique, given that collisions overwrite and that CloudKit sync drops the guarantee.
## What @Attribute does In SwiftData every stored property of a `@Model` class is an **attribute**, and the default behaviour suits most of them. When one property needs different treatment you annotate it with `@Attribute`, a peer macro whose iOS 27 SDK signature is `Attribute(_ options: Schema.Attribute.Option..., originalName: String? = nil, hashModifier: String? = nil)`, available since iOS 17. The options are variadic, so one property can carry several. `originalName` maps a renamed property onto its old stored name; that belongs to the lesson on schema migrations. ## .unique: uniqueness by update, not by error `@Attribute(.unique) var name: String` declares that no two `Habit` records may share a name. What happens on a collision is the part interviewers probe. Apple's earthquake sample describes the sequence, and a test with an in-memory store on macOS 27 behaved the same way: 1. Code creates a new `Habit` named "Run" and inserts it into the context. 2. The context saves, explicitly or through autosave. 3. SwiftData checks whether a stored `Habit` already has the name "Run". 4. If one does, SwiftData updates that stored record's other properties with the new object's values; if not, it adds a new record. The consequences: - There is **no constraint error to catch**; the last write wins. - It is a convenient **insert-or-update** for importing server data keyed by a stable identifier, which is exactly how Apple's sample uses it. - It is a trap when two genuinely different things collide, because one silently overwrites the other. - `.unique` covers **one property**. A rule over two properties together needs the `#Unique` macro added in iOS 18. - Apple's documentation lists unique constraints among the features CloudKit cannot enforce, so a synced store cannot rely on it. ## .externalStorage: large bytes outside the database `@Attribute(.externalStorage) var photo: Data?` asks SwiftData to keep the value outside the database file itself. In a test store on macOS 27, a 2 MB `photo` landed as its own file in a hidden support folder beside the `.store` file, while the database stayed small. The property is still an ordinary `Data?` in Swift; only where the bytes live changes. It suits images, audio and other large blobs, and keeps large values out of the rows a fetch reads. ## The other options | Option | What it asks for | Typical use | |---|---|---| | `.unique` | One record per value; a duplicate save updates | Server IDs, natural keys | | `.externalStorage` | Store the bytes outside the database | Photos, audio | | `.transformable(by:)` | Store a non-Codable type through a `ValueTransformer` | `UIColor` and similar classes | | `.preserveValueOnDeletion` | Keep the value after the model is deleted | A stable ID read from history tombstones | | `.spotlight` | Index the value for Spotlight | Searchable titles | | `.allowsCloudEncryption` | Encrypt the value in CloudKit | Sensitive notes in a synced store | Two details matter for `.transformable(by:)`: it takes either a `ValueTransformer` subclass or the name of a registered transformer, and the transformer has to be registered with `ValueTransformer` before the store loads. In a test without registration, SwiftData stopped with the fatal error "Application must register a ValueTransformer for ColorTransformer". `.preserveValueOnDeletion` pays off with the history API added in iOS 18, which reads the kept value from a deleted model's tombstone. ## Choosing what to mark unique Because a collision overwrites rather than fails, the choice of key decides whether `.unique` helps or hurts: - A **server-assigned identifier** that never changes is the ideal key: re-importing the same payload updates records instead of duplicating them. - A **user-typed name** is riskier. Two habits a person happens to name "Run" collapse into one record, and the second one's goal and photo replace the first's without any prompt. Validate the name in the UI before inserting if that matters. - A **value that can change**, such as an email address, makes a poor key, because editing it can collide with another record. In an interview, say which of these your key is and what happens to the losing record. ## Mistakes to avoid - Wrapping `save()` in `do`/`catch` to detect duplicates on a `.unique` property; nothing is thrown. - Putting `.unique` on two properties and expecting the pair to be unique; each becomes unique on its own. - Adding `.unique` to a store that already holds duplicates without planning the data fix, which is a migration problem. - Treating `.externalStorage` as compression; it changes where bytes live, not their size.
- Why can't a SwiftData store synced through CloudKit rely on @Attribute(.unique)?Apple's documentation lists unique constraints among the SwiftData features CloudKit does not support natively: the framework syncs changes concurrently and at opportune times, so CloudKit cannot enforce the option. A synced schema leaves `.unique` off and handles duplicates in app code. Setting up the sync itself is covered with CloudKit.
- When would you use .transformable(by:) instead of making the type Codable?When the type cannot reasonably be `Codable`, typically a class such as `UIColor` that supports secure coding. Pass a `ValueTransformer` subclass, for example one derived from `NSSecureUnarchiveFromDataTransformer`, or a registered transformer's name, and register the transformer with `ValueTransformer` before the container loads; otherwise SwiftData stops with a fatal error asking the app to register it.
- How do you make an import of server records idempotent with @Attribute(.unique)?Mark the server's stable identifier `.unique`, build a model for every record in the payload and insert each one. On save, records whose identifier already exists are updated and new ones are added, so running the same import twice leaves one record per identifier. It only works when the server guarantees that identifier is stable.
- Saving a duplicate .unique value throws an error you can catch.
- Putting .unique on two properties makes the pair a compound key.
- .externalStorage compresses the data inside the database row.
- CloudKit sync enforces @Attribute(.unique) across devices.
- .transformable(by:) works without registering the transformer.