SwiftData Unidirectional Relationships

Hi everyone

I would like to achieve having unidirectional relationships in my SwiftData project (which I believe is possible: https://developer.apple.com/documentation/updates/swiftdata?changes=_9) but I'm afraid I'm struggling to overcome the errors I'm experiencing.

For example, I have the following models:

@Model
final class Quota {
    @Attribute(.unique) var id: UUID
    var allowance: Int
    @Relationship(inverse: nil) var fish: Fish

    init(id: UUID = UUID(), fish: Fish, allowance: Int) {
        self.id = id
        self.fish = fish
        self.allowance = allowance
    }
}

@Model
final class Fish {
    @Attribute(.unique) var id: Int
    var name: String
    init(id: Int, name: String) {
        self.id = id,
        self.name = name
    }
}

However, when I attempt to save a quota as so:

let quota: Quota = .init(fish: Fish(id: 2, name: "Salmon"), allowance: 50)
modelContext?.insert(quota)
try save()

I keep getting the following error:

SwiftData.DefaultStore save failed with error: Error Domain=NSCocoaErrorDomain Code=1570 "%{PROPERTY}@ is a required value." UserInfo={NSValidationErrorObject=<NSManagedObject: 0x600002217390> (entity: Fish; id: 0x83319d001151328d <x-coredata://C76A2A64-146E-432F-A565-319B5A2F23F5/Fish/p12>; data: { id = nil; }), NSLocalizedDescription=%{PROPERTY}@ is a required value., NSValidationErrorKey=id, NSValidationErrorValue=null} %{PROPERTY}@ is a required value.

However, if I set up Quota and Fish with an inverse relationship then the data saves as expected, so I'm a little confused. Is there anyone out there who can provide some guidance as to why I'm seeing this error when I try to save a record in SwiftData with no inverse relationship?

I do fully understand about unidirectional vs bidirectional relationships but I have a scenario where I need the relationship to be unidirectional. Also, as a side note, the Fish record already exists in my database, but if I delete it and try to save the record I still see this error.

Thank you so much in advance for any help.

The error seems to be triggered the second time when a Fish is added, which is because Fish(id: 2, name: "Salmon") uses a duplicate value (2) for the id attribute, which is .unique.

Avoiding using a duplicate value for the .unique attribute fixes the error. I've confirmed that Xcode 26.2 (17C52) on iOS Simulator 26.2 (23C54).

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

SwiftData Unidirectional Relationships
 
 
Q