How to copy a “Dictionary” in Swift?

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]

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)