【发布时间】:2015-03-24 12:47:10
【问题描述】:
考虑两个类。第一个是Vehicle,一个符合NSCopying的NSObject子类:
class Vehicle : NSObject, NSCopying {
var wheels = 4
func copyWithZone(zone: NSZone) -> AnyObject {
let vehicle = self.dynamicType()
vehicle.wheels = self.wheels
return vehicle
}
}
第二个类Starship继承自Vehicle:
class Starship : Vehicle {
var photonTorpedos = 6
var antiGravity = true
override func copyWithZone(zone: NSZone) -> AnyObject {
let starship = super.copyWithZone(zone) as Starship
starship.photonTorpedos = self.photonTorpedos
starship.antiGravity = self.antiGravity
return starship
}
}
此代码无法编译,因为:
使用元类型值构造类类型“Vehicle”的对象必须使用“必需”初始化程序。
所以我继续添加一个必需的初始化程序:
required override init () {
super.init()
}
现在应用编译,Starship 对象正确响应copy()。
两个问题:
- 为什么用元类型构造对象需要
required初始化器? (看来我写的初始化程序什么也没做。) - 我写错了什么,或者应该添加到初始化程序中吗?有没有我没有考虑的案例?
【问题讨论】:
标签: swift introspection