How to do “Deep Copy” in Swift?

后端 未结 3 1112
死守一世寂寞
死守一世寂寞 2020-12-08 20:46

In Objective-C, one can deep-copy by following:

 Foo *foo = [[Foo alloc] init];
 Foo *foo2 = foo.copy;

How to do this deep-copy in Swift?

3条回答
  •  甜味超标
    2020-12-08 21:14

    To My Forgetful Future Self:

    For anyone else looking for an easy way to do deep copy of a tree-style object with Swift (parent may/may not have children and those children may/may not have children & so on)…

    If you have your classes set up for NSCoding (for persistent data between launches), I was able to use that ability to do a deep copy of any particular instance of this tree structure by doing the following…

    (Swift 4)

    class Foo: NSObject, NSCoding {
       var title = ""
       var children: [Foo] = []
    
       *blah, blah, blah*
    
       // MARK: NSCoding
       override public func encode(with coder: NSCoder) {
          super.encode(with: coder)
          coder.encode(title as Any?, forKey: "title")
          coder.encode(children as Any?, forKey: "children")
       }
    
       required public init?(coder decoder: NSCoder) {
          super.init(coder: decoder)
          self.title = decoder.decodeObject(forKey: "title") as? String ?? ""
          self.children = decoder.decodeObject(forKey: "children") as? [Foo] ?? []
       }
    
    }
    

    Meanwhile… Elsewhere…

    // rootFoo is some instance of a class Foo that has an array of child Foos that each can have their own same array
    
    // Archive the given instance
    let archive = NSKeyedArchiver.archivedData(withRootObject: rootFoo)
    
    // Unarchive into a new instance
    if let newFoo = NSKeyedUnarchiver.unarchiveObject(with: archive) as? Foo {
    
       // newFoo has identical copies of all the children, not references
    
    }
    

提交回复
热议问题