hi,
bob makes a decent point: if you're really working with essentially a one-to-many relationship, where the one "owns" the many, put one struct inside the other, although the size of that struct might become prohibitive to copy around, perhaps. but this may not be exactly your situation; and frankly, storing an id in one struct
in order to locate a related struct
somewhere else is not unique to struct
s.
for example, Apple has posted some sample code on how to configure Core Data with both a "cloud" and a "local" store, yet still implement a relationship from an object in one of those stores to one in the other store. the key is that an object in one store maintains the id of a related object in the other store, and finding one from the other is implemented using a Core Data fetch (essentially, an optimized firstIndex
function).
if you do wish to go the id/lookup route, e.g., to find the person that owns a given dog (with a given id), you could do a similar firstIndex
lookup of the people array; but you could also implement a dictionary of type [UUID : Int]
in your House struct to quickly locate the correct index within the people array for the dog having the given id. yes, the dictionary would require a little maintenance, but mostly just for adds and deletes, and it would not be much work even if you rebuild it when necessary:
func rebuildLookupDictionary() {
lookupDictionary.removeAll()
for index in people.indices {
lookupDictionary[person[index].favoriteDogID] = index
}
}
func person(owning dog: Dog) -> Person {
let index = lookupDictionary[dog.id]!
return people[index]
}
hope that helps,
DMG