Search code examples
swiftmodelswiftdata

Is it possible to make strong reference cycles using SwiftData?


Almost on all tutorials I have seen of SwiftData they relate @Models between each others. Is it possible to make strong reference cycles using SwiftData? Or is it enough by marking them as @Relationship(deleteRule: .cascade) or nullify?

Example.

@Model
class Country {
 var name: String
 var states: [State]

 init(...)...
} 

@Model
class State {
 var name: String
 var country: Country

 init(...)...
} 

Solution

  • The models don't store the relationships by themselves, behind the scenes the storage is resolved by the ModelContext. Thus, even circular relationships are safe from this point of view (retain cycles).

    @Relationship(deleteRule: .cascade) is needed only if your database rules require the related models to also be deleted.