GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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 RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.

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.