Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a reference to a Dictionary in Swift

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?

like image 886
Rodrigo Avatar asked Sep 25 '22 14:09

Rodrigo


1 Answers

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.

like image 100
Charles A. Avatar answered Sep 28 '22 05:09

Charles A.