How to copy a “Dictionary” in Swift?

后端 未结 3 624
执笔经年
执笔经年 2021-01-01 10:36

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

3条回答
  •  爱一瞬间的悲伤
    2021-01-01 11:11

    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]

提交回复
热议问题