1

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?

HangarRash
  • 7,314
  • 5
  • 5
  • 32
  • I don't have a definite answer for this but not that SwiftData will manage the relationships for you, if you assign a parent to a child then SwiftData will handle the inverse so that the child will be added to the children array. And there is also the logic for faulting which is also relevant here. – Joakim Danielson Jul 05 '23 at 08:25

0 Answers0