How to do “Deep Copy” in Swift?

后端 未结 3 1111
死守一世寂寞
死守一世寂寞 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:09

    If Foo is an Objective-C class that implements NSCopying, then the following will work:

    var foo2 = foo.copy();
    

    -copy is not defined using property notation in Foundation, so you can't treat it as a property in Swift even though you can use dot notation in Objective-C. In fact, you really shouldn't use dot notation (even though it is syntactically legal) because -copy is not logically a property of the object, it is a method taking no parameters that manufactures a copy of the object.

    NB this is not a deep copy, just as it is not a deep copy in Objective-C unless the implementation also copies all the members of the Foo instance.

提交回复
热议问题