Xcode 16.0. SwiftData Schema Fatal error: Inverse already set to another relationship

Hi, after upgrading to Xcode 16.0 I encountered the fact that when loading preview, I get an error:

Fatal error: Inverse already set to another relationship - secondAccount - cannot assign to - firstAccount

import Foundation
import SwiftData
import SwiftUI

@Model
class TransactionModel {
    @Relationship(inverse: \AccountModel.accountTransactions) var firstAccount: AccountModel? /// <- here
    @Relationship(inverse: \AccountModel.accountTransactions) var secondAccount: AccountModel? /// <- here
    @Relationship(inverse: \DebtorModel.transactions) var debtor: DebtorModel?
    @Relationship(inverse: \CategoryModel.transactions) var category: CategoryModel?

    init(account: AccountModel? = nil, secondAccount: AccountModel? = nil, debtor: DebtorModel? = nil, category: CategoryModel? = nil) {
        self.firstAccount = account
        self.secondAccount = secondAccount
        self.debtor = debtor
        self.category = category
    }
}
import SwiftData
import SwiftUI

@Model
final public class AccountModel: Identifiable, Hashable {
    
    var accountId: UUID = UUID()

    var accountTransactions: [TransactionModel]?
    
    init(id: UUID = UUID()) {
        self.accountId = id
    }
}

Is this really not possible to implement? In Xcode 15, this worked both on the device and in the editor.

Thanks!

Answered by DTS Engineer in 804427022

Xcode 16 reporting the error is a correct behavior to me, because in SwiftData, a relationship and its inverse must be a one to one pair. You code tries to set AccountModel.accountTransactions as the inverse relationship of both firstAccount and secondAccount, which is unsupported.

You can consider consolidate firstAccount and secondAccount to something like accounts: [AccountModel]?, which makes it a many-to-many relationship. Thay way, a transaction model won't be constrained to have only two accounts, but should be good enough for your use case.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Accepted Answer

Xcode 16 reporting the error is a correct behavior to me, because in SwiftData, a relationship and its inverse must be a one to one pair. You code tries to set AccountModel.accountTransactions as the inverse relationship of both firstAccount and secondAccount, which is unsupported.

You can consider consolidate firstAccount and secondAccount to something like accounts: [AccountModel]?, which makes it a many-to-many relationship. Thay way, a transaction model won't be constrained to have only two accounts, but should be good enough for your use case.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Xcode 16.0. SwiftData Schema Fatal error: Inverse already set to another relationship
 
 
Q