Understanding init() when sub-classing in Swift

920 views Asked by At

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 Vehicleclass, 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)
1

There are 1 answers

2
dfrib On BEST ANSWER

Any designated initializer in a subclass must call a designated initializer from its immediate superclass:

Initializer Delegation for Class Types

To simplify the relationships between designated and convenience initializers, Swift applies the following three rules for delegation calls between initializers:

Rule 1 A designated initializer 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 and engine, and use the latter to inititalize the member property engine of the subclass, thereafter call the designated initializer of the superclass using the supplied make parameter (supplied to subclass initializer) as argument to the superclass initializer.

class Car: Vehicle {
    var engine: Double

    init(make: String, engine:Double){
        self.engine = engine
        super.init(make: make)
    }
}