<!--
{
  "availability" : [
    "iOS: 18.0.0 -",
    "iPadOS: 18.0.0 -",
    "macCatalyst: 18.0.0 -",
    "macOS: 15.0.0 -",
    "swift: 5.9.0 -",
    "tvOS: 18.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 11.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "SwiftData",
  "identifier" : "/documentation/SwiftData/Unique(_:)",
  "metadataVersion" : "0.1.0",
  "role" : "Macro",
  "symbol" : {
    "kind" : "Macro",
    "modules" : [
      "SwiftData"
    ],
    "preciseIdentifier" : "s:9SwiftData6UniqueyySays14PartialKeyPathCyxGGd_tcAA15PersistentModelRzlufm"
  },
  "title" : "Unique(_:)"
}
-->

# Unique(_:)

Specifies the key-paths that SwiftData uses to enforce the uniqueness of model
instances.

```
@freestanding(declaration) macro Unique<T>(_ constraints: [PartialKeyPath<T>]...) where T : PersistentModel
```

## Parameters

`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.

> Important: For relationship attributes, SwiftData only supports unique
> constraints on those that reference a single persistent model, rather than an
> array of persistent models.

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`:

```swift
@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
    }
}
```

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)