Protocol func returning Self

后端 未结 9 1897
悲哀的现实
悲哀的现实 2020-11-22 15:11

I have a protocol P that returns a copy of the object:

protocol P {
    func copy() -> Self
}

and a class C that implements P:



        
9条回答
  •  渐次进展
    2020-11-22 16:01

    Following on Rob's suggestion, this could be made more generic with associated types. I've changed the example a bit to demonstrate the benefits of the approach.

    protocol Copyable: NSCopying {
        associatedtype Prototype
        init(copy: Prototype)
        init(deepCopy: Prototype)
    }
    class C : Copyable {
        typealias Prototype = C // <-- requires adding this line to classes
        required init(copy: Prototype) {
            // Perform your copying here.
        }
        required init(deepCopy: Prototype) {
            // Perform your deep copying here.
        }
        @objc func copyWithZone(zone: NSZone) -> AnyObject {
            return Prototype(copy: self)
        }
    }
    

提交回复
热议问题