How to copy a "Dictionary" in Swift?

allenlinli picture allenlinli · Jul 18, 2014 · Viewed 24k times · Source

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,

Answer

ikuramedia picture ikuramedia · Jul 18, 2014

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]