I am working with a complex dictionary and want to make it easy to work just assigning a variable to it.
myDictionay["with"]["complex"]["sub"]["dictionary"] = "NewValue"
I just want this:
let smaller = myDictionay["with"]["complex"]["sub"]
smaller["dictionary"] = "NewValue"
How can I do it?
The Swift Dictionary
(and Array
/ Set
) follows pass by reference semantics, rather than pass by value semantics (if you look in the headers you'll see it is a struct
, not a class
). This means that when you assign a Dictionary
instance from one variable to another variable, and change the value associated with the new variable, it does not in fact change the value associated with the original value. As such, the syntax you are looking for is not possible with a Swift Dictionary
. Having said that, you can always use an NSMutableDictionary
instead, and then the syntax you are hoping for will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With