How to copy a \"Dictionary\" in Swift?
That is, get another object with same keys/values but different memory address.
Furthermore, how to copy an object in
All of the answers given here are great, but they miss a key point regarding warning you about the caveats of copying.
In Swift, you have either value types (struct, enum, tuple, array, dict etc) or reference types (classes).
If you need to copy a class object, then, you have to implement the methods copyWithZone
in your class and then call copy on the object.
But if you need to copy a value type object, for eg. an Array you can copy it directly by just assigning it to a new variable like so:
let myArray = ...
let copyOfMyArray = myArray
But this is only shallow copying.
If your array contains class objects and you want to make their copy as well then you have to copy each array element individually. This will allow you to make a deep copy.
This is extra information that I thought would add to the information already presented in the well-written answers above.