Implementing copy() in Swift

The copy method is defined in NSObject. If your custom class does not inherit from NSObject, copy won’t be available.

You can define copy for any object in the following way:

class MyRootClass {
    //create a copy if the object implements NSCopying, crash otherwise

    func copy() -> Any {
        guard let asCopying = ((self as AnyObject) as? NSCopying) else {
            fatalError("This class doesn't implement NSCopying")
        }

        return asCopying.copy(with: nil)
    }
}

class A : MyRootClass {

}

class B : MyRootClass, NSCopying {

    func copy(with zone: NSZone? = nil) -> Any {
        return B()
    }
}


var b = B()
var a = A()

b.copy()  //will create a copy
a.copy()  //will fail

I guess that copy isn’t really a pure Swift way of copying objects. In Swift it is probably a more common way to create a copy constructor (an initializer that takes an object of the same type).

Leave a Comment