Implementing copy() in Swift

前端 未结 10 1449
难免孤独
难免孤独 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:11

    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).

提交回复
热议问题