如何在Swift子类中实现复制构造函数?

如何在Swift子类中实现复制构造函数?,第1张

如何在Swift子类中实现复制构造函数?

init(copyFrom: Square)
是的重载,而不是覆盖
init(copyFrom:Shape)
。我的意思是,它们是不相关的方法,因为它们接受不同的类型。在Swift中这是可以接受的。在ObjC中,这是非法的。ObjC中没有重载。

Swift初始化器不会自动继承。因此,在Swift中,您不能尝试将random复制

Shape
Square
。初始化器不可用。但是在ObjC中,初始化器

自动继承(您不能阻止它们这样做)。因此,如果您有一个方法
initWithCopyFrom:(*Shape)
,则要求每个子类都愿意接受它。这意味着您可以(在ObjC中)尝试创建一个Circle作为Square的副本。那当然是胡说八道。

如果这是

NSObject
子类,则应使用
NSCopying
。这是您的处理方式:

import Foundationclass Shape : NSObject, NSCopying { // <== Note NSCopying  var color : String  required override init() { // <== Need "required" because we need to call dynamicType() below    color = "Red"  }  func copyWithZone(zone: NSZone) -> AnyObject { // <== NSCopying    // *** Construct "one of my current class". This is why init() is a required initializer    let theCopy = self.dynamicType()    theCopy.color = self.color    return theCopy  }}class Square : Shape {  var length : Double  required init() {    length = 10.0    super.init()  }  override func copyWithZone(zone: NSZone) -> AnyObject { // <== NSCopying    let theCopy = super.copyWithZone(zone) as Square // <== Need casting since it returns AnyObject    theCopy.length = self.length    return theCopy  }}let s = Square()      // {{color "Red"} length 10.0}let copy = s.copy() as Square // {{color "Red"} length 10.0} // <== copy() requires a casts.color = "Blue"    // {{color "Blue"} length 10.0}s        // {{color "Blue"} length 10.0}copy     // {{color "Red"}

迅捷3

class Shape: NSObject, NSCopying {    required override init() {        super.init()    }    func copy(with zone: NSZone? = nil) -> Any {        let copy = type(of: self).init()        return copy    }}class Square: Shape {    required override init() {        super.init()    }    func copy(with zone: NSZone? = nil) -> Any {        let copy = super.copy(with: zone) as! Square        copy.foo = self.foo        ......        return copy    }}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5642214.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存