My use case is based on the following model:
struct Person { let name: String let houses: [House] } struct House { let owner: Person }
Now, ideally, I would like to maintain a bi-directional relationship in which each house should have exactly one owner, where the owner should also know all his houses.
Using the above data structures, is it possible to create House and Person instances in such a way that there is a relationship between them, and the objects essentially point to each other?
I assume that the wording of this is already somewhat misleading, because because of the semantics of the values ββof struct s, they actually do not indicate anything, but contain only copies of the values. It seems like it should be obvious that it's impossible to create these two objects with a bi-directional ratio, but I still wanted to be sure and ask the following questions here!
The obvious solution would also be to make the houses and owner variables using var instead of let when declaring them, then communication can be maintained in the initializer of each struct :
struct Person { let name: String var houses: [House] init(name: String, houses: [House]) { self.name = name self.houses = houses self.houses = houses.map { (house: House) in var newHouse = house newHouse.owner = self return newHouse } } } struct House { var owner: Person init(owner: Person) { self.owner = owner var newHouses = self.owner.houses newHouses.append(self) self.owner = Person(name: owner.name, houses: newHouses) } }
However, what if I want to keep the houses and owner constant? As I said, it seems obvious that this is impossible, but I wonder if there is any weird (possibly functional) way to achieve this? I was thinking about lenses , which can be used as getters and setters when working with immutable models.