Magnus Magnus - 6 months ago 8x
Swift Question

Update dictionary with previously deleted items

I have two dictionaries. Both declared in a viewController, both based on a model structure class.

// ItemDictionary
var ItemDictionary = ItemModel()
var JSONDictionary = ItemModel()

JSON data is fed into the JSONDictionary and then this data is passed to ItemDictionary which feeds a table within ViewDidLoad.

self.ItemDictionary = self.JSONDictionary

All good. The table is nicely populated from JSON data. I can also delete items from the table and the ItemDictionary. However, when I try and add items back by referring to the original dictionary (JSONDictionary) the item has gone.

I understand this is expected. If Dictionary1 = Dictionary2, a new dictionary is not actually created. Only an second address. So if you change Dictionary1, Dictionary2 also changes.

A practical example could be setting a price range. You can reduce the range and have less items displayed on the table. But you can't replace previously deleted items if you wanted to increase the price range. I do not want to recall the JSON script each time I edit the range. Advice appreciated.


As confirmed by the OP, ItemModel is a class and not a Dictionary. To fix this you need to make ItemModel a real Dictionary and thus a value type. This is probably the preferred choice but will be more work.

An alternative would be to add an convenience initializer to the ItemModel class that instantiates a new copy of itself and call that instead of setting self.ItemDictionary = self.JSONDictionary.

Something like this.

init(model: ItemDictionary) -> ItemDictionary {
   // copy properties

Then create the new copy.

self.ItemDictionary = ItemDictionary(self.JSONDictionary)

Later you can reinitialize ItemDictionary with the same call.