Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a "Dictionary" in Swift?

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 Swift?

Thanks,

like image 636
allenlinli Avatar asked Jul 18 '14 03:07

allenlinli


People also ask

How dictionary works internally Swift?

dictionary in Swift is used to store elements. Dictionary also contains one key while storing elements to it, later on, we can use these keys to access the elements store in the dictionary. Dictionary in swift does not maintain the insertion order of the element in which they are stored, they are unordered in nature.


2 Answers

A 'Dictionary' is actually a Struct in swift, which is a value type. So copying it is as easy as:

let myDictionary = ... let copyOfMyDictionary = myDictionary 

To copy an object (which is a reference type) has a couple of different answers. If the object adopts the NSCopying protocol, then you can just do:

let myObject = ... let copyOfMyObject = myObject.copy() 

If your object doesn't conform to NSCopying then you may not be able to copy the object. Depending on the object's class it may provide it's own method to get a duplicate copy, or if the object has no internal private state then you could create a new object with the same properties.

[Edited to correct a mistake in the previous answer - NSObject (both the Class and the Protocol) does not provide a copy or copyWithZone method and therefore is insufficient for being able to copy an object]

like image 53
ikuramedia Avatar answered Sep 19 '22 09:09

ikuramedia


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.

like image 35
jarora Avatar answered Sep 19 '22 09:09

jarora