LAST CHANCE: Save 50% on all my Swift books and bundles! >>

Day 12 - Question re class inheritance exercise

Forums > 100 Days of SwiftUI

class Instrument {
    var name: String
    init(name: String) {
        self.name = name
    }
}
class Piano: Instrument {
    var isElectric: Bool
    init(isElectric: Bool) {
        self.isElectric = isElectric
        super.init(name: "Piano")
    }
}

is there a reason why in the Piano initaliser we do not add name: String since it is inhereting from Instrument ? This is from question 9 from section 3 of Day 12

Thanks a lot

   

@coast asks:

is there a reason why in the Piano initaliser we do not add name: String ?
since it is [is it] inheriting from Instrument ?

Ask yourself, What is the purpose of an initialiser?

The initialiser for a class has one job: Provide a value for each of the classes' parameters.

The Instrument class requires a String for its name parameter.
The Piano class requires a Bool for its isElectronic parameter.

When you create a new Piano object, you must provide a boolean value to the initialiser. However, inside the initialiser you provide a default value--Piano-- for the object's name. Because you provide a default, you are not required to ask the programmer to provide a value for the name parameter in the initialiser.

Keep Coding

🎹⚡️

   

Super helpful thank you

   

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.