Consider two classes. The first is Vehicle
, an NSObject
subclass that conforms to NSCopying
:
class Vehicle : NSObject, NSCopying {
var wheels = 4
func copyWithZone(zone: NSZone) -> AnyObject {
let vehicle = self.dynamicType()
vehicle.wheels = self.wheels
return vehicle
}
}
The second class, Starship
, inherits from 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
}
}
This code doesn't compile because:
Constructing an object of class type 'Vehicle' with a metatype value must use a 'required' initializer.
So I go ahead and add a required initializer:
required override init () {
super.init()
}
And now the app compiles, and Starship
objects respond to copy()
properly.
Two questions:
- Why does constructing an object with a metatype need a
required
initializer? (It appears the initializer I wrote does nothing.) - Is there anything I wrote incorrectly, or should add to the initializer? Is there a case I'm not considering?