我有以下的例子在斯威夫特游乐场,企图实现雨燕拷贝构造函数:如何在Swift子类中实现复制构造函数?
class Shape : NSObject {
var color : String
override init() {
color = "Red"
}
init(copyFrom: Shape) {
color = copyFrom.color
}
}
class Square : Shape {
var length : Double
override init() {
super.init()
length = 10.0
}
init(copyFrom: Square) { /* Compilation error here! */
super.init(copyFrom: copyFrom)
length = copyFrom.length
}
}
let s : Square = Square() // {{color "Red"} length 10.0}
let copy = Square(copyFrom: s) // {{color "Red"} length 10.0}
s.color = "Blue" // {{color "Blue"} length 10.0}
s // {{color "Blue"} length 10.0}
copy // {{color "Red"} length 10.0}
的问题是,这实际上并不在其目前的形式编译。论Square
子类中的方法init(copyFrom: Square)
,报告这个错误:
Overriding method with selector 'initWithCopyFrom:' has incompatible type '(Square) -> Square'
这个问题将使意义,如果它不是一个构造,就好像它是一个普通func
,你可以可能会传入超类中预期的类型,但在子类中被覆盖的类型更具限制性:
let mySquare : Shape = Square() // Note the var is a SHAPE
mySquare.someShapeMethod("Test") // If Square overrides someShapeMethod() to expect Int, compiler errors out to protect us here.
但是,构造函数构造函数使我相信我应该能够覆盖它并提供不同的方法签名,因为在编译时绝对知道对象的类型是什么。
如果我将Shape
更改为不再延伸NSObject
,则此问题将消失。但是,由于包含现有的Objective-C代码,它需要扩展NSObject
。
我如何更新我的拷贝构造函数允许Shape
知道它是从一个Shape
复制,并允许Square
知道它是从一个Square
复制?
感谢罗布 - 可靠的答案。 – 2014-09-12 13:32:41
你也可能会发现这个讨论对于在纯Swift中制作副本很有用:http://stackoverflow.com/questions/25645090/protocol-func-returning-self – 2014-09-12 13:41:17
对于Swift 2/Xcode 7,它会是'let theCopy = self。 dynamicType.init()',当然'as!'而不是'as'(仅仅提到,因为相关的问题出现在这里:http://stackoverflow.com/questions/31885231/using-object-initializers-in-迅速更换的-allocwithzone)。 – 2015-08-07 19:53:56