What Happens When You Copy a Swift Dictionary?
This was the second show in a row talking about the Swift Programming Language. As part of the discussion, they talked about classes and structs in the language. During the discussion, it came up that in Swift, a Dictionary is a value type. That means if you assign a dictionary variable to another variable, it makes a copy. If you do that with a normal object, both variables just hold a pointer to the same spot in memory. If you change one, you change them both.
Well, the question came up that was basically, “If you have a dictionary full of objects and you assign it to another variable, will the objects be copied or referenced?”. The hosts could guess, but didn’t really know. I thought that it would be fun to try to find out. To do so, I wrote the following code in a Swift Playground in Xcode.
Here are the respective outputs:
Are originalFoo and referencedFoo the same object? true
Are originalFoo and anotherFoo the same object? false
Are referencedFoo and anotherFoo the same object? false
Are the values for first keys in the two dictionaries the same object? true
Are the values for second keys in the two dictionaries the same object? true
Is the value of the first key in the original dictionary the same object as the value of the second key in the copied dictionary? false
So, you can see that a dictionary struct is created, but it is just populated with references to the exact same Swift objects that were in the original dictionary. Playgrounds are pretty useful for just trying out code and testing these kinds of things. This is what I always used LINQPad for in .Net and I’m glad that this is available to us in Xcode.