How can I add a custom initializer when inheriting from a class that already has an initializer?
What I have is a Vehicle
class which has an itializer who takes an argument name
. What I want to do is inherit from this Vehicle
class, create another initializer for the new class but keep using the existing initializer.
Base Class (No problem here):
class Vehicle{
var make:String
init(make:String){
self.make = make
}
}
New Class (Doesn't work):
// Not sure how to structure this class
class Car:Vehicle {
var engine:Double
override init(){
super.init()
}
init(engine:Double){
self.engine = engine
}
}
This is what I would like to be able to do... re-use the existing initializer plus the new one.
let cobalt = Car(make:"Chevy" engine: 2.5)
Any designated initializer in a subclass must call a designated initializer from its immediate superclass:
From the Swift Language Guide - Initialization.
Hence, you could construct your designated initializer of
Car
to take two arguments,make
andengine
, and use the latter to inititalize the member propertyengine
of the subclass, thereafter call the designated initializer of the superclass using the suppliedmake
parameter (supplied to subclass initializer) as argument to the superclass initializer.