Unique(_:)
Specifies the key-paths that SwiftData uses to enforce the uniqueness of model instances.
Declaration
@freestanding(declaration) macro Unique<T>(_ constraints: [PartialKeyPath<T>]...) where T : PersistentModelParameters
- constraints:
Arrays of model key-paths that form the unique constraints to apply to the enclosing model.
Overview
If a model class contains attributes that you require to be unique across all persisted instances of that model, add the Unique macro to that model’s definition. You can specify a constraint on a single attribute, a compound constraint across multiple attributes, or any combination of the two.
The following example declares that every instance of Person has a unique id, and that no two instances of Person have the same givenName and familyName:
@Model
final class Person {
// Declare any unique constraints as part of the model definition.
#Unique<Person>([\.id], [\.givenName, \.familyName])
var id: UUID
var givenName: String
var familyName: String
init(id: UUID, givenName: String, familyName: String) {
self.id = id
self.givenName = givenName
self.familyName = familyName
}
}