How to copy a “Dictionary” in Swift?

百般思念 提交于 2019-12-18 14:13:30

问题


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,


回答1:


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]




回答2:


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 you copy a value type object, for eg. and 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.




回答3:


Object

class Person: NSObject, NSCopying {
    var firstName: String
    var lastName: String
    var age: Int

    init(firstName: String, lastName: String, age: Int) {
        self.firstName = firstName
        self.lastName = lastName
        self.age = age
    }

    func copyWithZone(zone: NSZone) -> AnyObject {
        let copy = Person(firstName: firstName, lastName: lastName, age: age)
        return copy
    }
}

Usage

let paul = Person(firstName: "Paul", lastName: "Hudson", age: 35)
let sophie = paul.copy() as! Person

sophie.firstName = "Sophie"
sophie.age = 5

print("\(paul.firstName) \(paul.lastName) is \(paul.age)")
print("\(sophie.firstName) \(sophie.lastName) is \(sophie.age)")

Source: https://www.hackingwithswift.com/example-code/system/how-to-copy-objects-in-swift-using-copy



来源:https://stackoverflow.com/questions/24816754/how-to-copy-a-dictionary-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!