Relationship(_:deleteRule:minimumModelCount:maximumModelCount:originalName:inverse:hashModifier:)
Specifies the options that SwiftData needs to manage the annotated property as a relationship between two models.
Declaration
@attached(peer) macro Relationship(_ options: Schema.Relationship.Option..., deleteRule: Schema.Relationship.DeleteRule = .nullify, minimumModelCount: Int? = 0, maximumModelCount: Int? = 0, originalName: String? = nil, inverse: AnyKeyPath? = nil, hashModifier: String? = nil)Parameters
- options:
A list of options to apply to the annotated property to customize its behavior. For possible values, see Option.
- deleteRule:
The rule to apply when you delete the relationship’s owning persistent model. For possible values, see Deleterule Swift.enum. The default value is Nullify.
- minimumModelCount:
The minimum number of models the relationship can reference. The default value is
0. - maximumModelCount:
The maximum number of models the relationship can reference. The default value is
0. - originalName:
The previous name of the attribute, if it’s different to the one in the current schema version. The default value is
nil. - inverse:
The key path of the relationship that represents the inverse of this relationship. The default value is
nil. - hashModifier:
A unique hash value that represents the most recent version of the annotated property. The default value is
nil.
Mentioned in
Overview
If one or more of a model’s properties represent relationships between their containing model and another model, annotate those properties with the @Relationship macro. This enables SwiftData to enforce those relationships at runtime — including what happens if you delete related data – as well as write any associated metadata to the persistent storage so the relationships exist across app launches.
In the following example, a remote image may belong to a category, and a category can contain zero, one, or more images.
@Model
class RemoteImage {
@Attribute(.unique) var sourceURL: URL
@Relationship(inverse: \Category.images) var category: Category?
var data: Data
init(sourceURL: URL, data: Data = Data()) {
self.sourceURL = sourceURL
self.data = data
}
}
@Model
class Category {
@Attribute(.unique) var name: String
@Relationship var images = [RemoteImage]()
init(name: String) {
self.name = name
}
}For more information about defining relationships between models, see Defining data relationships with enumerations and model classes.