How to copy a “Dictionary” in Swift?

后端 未结 3 633
执笔经年
执笔经年 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:22

    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

提交回复
热议问题