UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

   

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.