栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在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    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636355.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号