Laurent Delorme Laurent Delorme - 3 years ago 186
Swift Question

Use of 'self' in property access 'model' before super.init initializes self super.init(brand: brand, model: model)

I'm following this tutorial : https://www.raywenderlich.com/160728/object-oriented-programming-swift

...and trying to make some personal adjustments to the code to see if I'm able to understand some core concepts on my own.

I end up with the following code :

class Instrument {

var brand: String
var model: String

init(brand: String, model: String) {

self.brand = brand
self.model = model

}

func tune() {

print("\(model) tuned !")
}

func play() {

print("\(model) plays an improvised melody")

}

func perform() {

print(tune())
print(play())
}

}


And this subclass :

class Piano: Instrument {

var hasPedals: Bool

init(hasPedals: Bool ) {

self.hasPedals = hasPedals
super.init(brand: brand, model: model)

}

}


At this point, I have the following error message :


Playground execution failed:

error: Object oriented programming.playground:28:41: error: use of
'self' in property access 'model' before super.init initializes self
super.init(brand: brand, model: model)
^

error: Object oriented programming.playground:28:27: error: use of
'self' in property access 'brand' before super.init initializes self
super.init(brand: brand, model: model)


I have the feeling that this is a super obvious mistake, but I can't figure out how to solve it.




Edit : Thanks a lot you guys for the super clean answers. It make a lot of sens to me now !

If I understand it correclty, even when you are using a custom init method in a subclass, you need to initialize all the stored properties (from both superclass and subclass) right ?

Answer Source

You are calling the superclass init method to initialize part of your subclass. However, before you have initialized it, you passed an uninitialized variable. Simply add those variables into the parameter of the Piano:

init(hasPedals: Bool, brand: String, model: String)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download