Normally, in a parent/child relationship, the parent
property in the Child
class would need to be weak
. For example:
class Parent {
var children: [Child]
}
class Child {
weak var parent: Parent?
}
This would be done to avoid reference cycles.
If I want to use these with SwiftData I would think it would be:
@Model
class Parent {
@RelationShip(inverse: \Child.parent)
var children: [Child]
}
@Model
class Child {
weak var parent: Parent?
}
But when looking as some sample code from WWDC23 (Backyard Birds: Building an app with SwiftData and widgets), I'm not seeing any use of weak
.
For example, there are, among others, classes named Plant
, PlantSpecies
, and Backyard
. Here's relevant excerpts from the classes:
@Model public class Plant {
@Attribute(.unique) public var id: String
public var creationDate: Date
public var species: PlantSpecies!
public var backyard: Backyard?
public var variant: Int
...
@Model public class Backyard {
@Attribute(.unique) public var id: String
public var name: String
@Relationship(inverse: \Plant.backyard)
public var leadingPlants: [Plant]
@Relationship(inverse: \Plant.backyard)
public var trailingPlants: [Plant]
...
@Model public class PlantSpecies {
@Attribute(.unique) public var id: String
public var parts: [PlantPart]
@Relationship(.cascade, inverse: \Plant.species)
public var plants: [Plant]
...
Why aren't species
and backyard
in the Plant
class set as weak
? Is this an oversight or is there something going on with SwiftData?