WWDC24 SALE: 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

   

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.