Repling to my own post to demo Explicit Relationships in both classes of a relationship.
I like to know at a glance that the attribute is part of a relationship.
Relationships in SwiftData are tricky and still evolving
IMPORTANT 2023-12-03 Only set the inverse relationship on one side, on one class, of the Example.
NOTE: The Optional "?" indicates that the attribute may be nil.
Remember to set appropriate Delete Rules for your situation, I set all below to nullify for consistency.
Example One to One: Country can have only One Capital City
Class with Only One: Country: capitalCity
@Relationship(deleteRule: .nullify) var capitalCity: City?
Class with Only One: City: country
@Relationship(deleteRule: .nullify) var country: Country?
Example One to Many: Company can have many Addresses
Class with only One: Address: company
@Relationship(deleteRule: .nullify) var company: Company?
Class with Many: Company: addresses
@Relationship(deleteRule: .nullify, inverse: \Address.company) var addresses: [Address]?
Example Many to Many: An Invoice can have many Receipts, and a Receipt can be split over many Invoices
Class with Many: Receipt - can only set inverse on one side!
@Relationship(deleteRule: .nullify) var invoices: [Invoice]?
Class with Many: Invoice: Inverse set here since it is more likely an Invoice will have more Receipts than having a Receipt split over many Invoices.
@Relationship(deleteRule: .nullify, inverse: \Receipt.invoices) var receipts: [Receipt]?