There are two approaches that I would use here. The first approach is to reconsider whether ShoppingList a value type or a reference type. The fact that it has an identifier tells me that it is indeed a reference type. If two shopping lists have the same content, should the same list be read? I suspect not. What does it mean to have two lists with the same identifier but with different content? If this is illegal, again, this indicates that it is a reference type because it has an identifier.
If it is a reference type, make it final class :
final class ShoppingList {}
Final classes keep structures simple because they do not suffer from inheritance problems. But they give referential semantics. With this change, your source code will work.
Another way to approach this is a more functional one, where everything is value. In this case, you can achieve this by copying copies of your shopping lists:
shoppingLists = shoppingLists.map { list in var newList = list newList.groceryItems = getGroceryItemsByShoppingList(list) return newList }
This pushes us to a more functional approach, but makes this identifier inconvenient. Therefore, if you really wanted to go this route, I would like to get rid of identifiers and, possibly, even make shopping lists unchanged. In this case, any two identical shopping lists are the same list, and you can write in a more functional style.
But I suspect that creating a ReferenceList ShoppingList is your best approach.
source share