Saleh Ahmadzada
Saleh Ahmadzada

Reputation: 45

How to rewrite an initializer in Swift for a subclass

Suppose that i have a class with default init() inside.

class Car { 
    var tires: Int
    var doors: Int
    init (tires: Int, doors: Int){
        self.tires = tires
        self.doors = doors 
    }
}

Then i am creating a subclass - BMW for example. BMW subclass will have its own unique variable for engine volume.

class BMW: Car {
    var volume: Int
    -------- type code here---------
}

I want to use init() of parent class, then add to that init() my volume variable, so that when i create an instance of subclass BMW, code will be like:

var newCar = BMW(tires: Int, doors: Int, volume: Int)

Note*: I do not want to hardcode any Value in subclass itself(using super.init()), i want to create totally new initializer.

Is it possible? If yes, could you please assist me?

Thanks.

Upvotes: 1

Views: 56

Answers (2)

vadian
vadian

Reputation: 285290

First initialize the volume property of the subclass, then call the designated initializer of the super class

class BMW: Car {
    var volume: Int

    init(tires: Int, doors: Int, volume: Int) {
        self.volume = volume
        super.init(tires: tires, doors: doors)
    }
}

Please read Swift Language Guide: Initialization and Inheritance

Upvotes: 1

Nima Yousefi
Nima Yousefi

Reputation: 817

You can just add a new initializer. Ideally, this should call up to the initializer you created for the Car class, using super.init(tires:doors:).

init(tires: Int, doors: Int, volume: Int) {
    self.volume = volume
    super.init(tires: tires, doors: doors)
}

Upvotes: 0

Related Questions