Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Object-Oriented Swift Inheritance Inheritance and Initializers

Giuseppe Santaniello
PLUS
Giuseppe Santaniello
Courses Plus Student 1,800 Points

optional parameter and hash symbol in a function

Hi, Amit in your example when you override the discounted Price function, you have inserted an underscore as optional parameter, but suppose that the function in the SuperClass has this signature:

func discountedPrice (#percentage: Double) -> Double{
    return price - (price * percentage / 100)
}

I don't need to insert the underscore as optional parameter, it's correct ?

In SubClass:

override func discountedPrice (percentage: Double = 10.0) -> Double{
   return super.discountedPrice(percentage: percentage)
}

Thanks, and sorry for my English ;)

2 Answers

Hi! I'm not Amit, but I hope I can help you anyway. I'm not sure why you assume he puts a hash symbol in the superclass initializer.

Product class initializer

func discountedPrice(percentage: Double) -> Double {
  return price - (price * percentage / 100)
}

There is no underscore before the percentage parameter, as it is nonoptional. A percentage must be specified.

Clothing class initializer

override func discountedPrice(_ percentage: Double = 10.0) -> Double {
    return super.discountedPrice(percentage) // Dry code FTW!
}

There is an underscore this time because a default value was specified. Amit explained: there is a narrow profit margin for clothing, so discounts are generally only 10%. Therefore, a good default value would be 10.0. If a percentage isn't specified, 10.0 will be used. If a percentage is specified, then that one will be used.

Hope I helped!

No problem. Good luck with your learning!