Implementing copy() in Swift

前端 未结 10 1452
难免孤独
难免孤独 2020-11-27 15:31

I want to be able to copy a custom class in Swift. So far, so good. In Objective-C I just had to implement the NSCopying protocol, which means implementing

10条回答
  •  清酒与你
    2020-11-27 16:20

    You can just write your own copy method

    class MyRootClass {
        var someVariable:Int
        init() {
            someVariable = 2
        }
        init(otherObject:MyRootClass) {
            someVariable = otherObject.someVariable
        }
        func copy() -> MyRootClass {
           return MyRootClass(self)
        }
    }
    

    The benefit of this is when you are using subclasses around your project, you can call the 'copy' command and it will copy the subclass. If you just init a new one to copy, you will also have to rewrite that class for each object...

    var object:Object
    ....
    //This code will only work for specific class
    var objectCopy = Object()
    
    //vs
    
    //This code will work regardless of whether you are using subClass or      superClass
    var objectCopy = object.copy()
    

提交回复
热议问题