Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Object-Oriented Swift Inheritance Overriding Methods

Shubham Batra
Shubham Batra
1,960 Points

overriding methods challenge

I don't know where did i go wrong. please tell me the correct answer to this challenge

Button.swift
class Button {
  var width: Double
  var height: Double

  init(width:Double, height:Double){
    self.width = width
    self.height = height
  }

  func incrementBy(points: Double){
    width += points
    height += points
  }
}

class RoundButton: Button {
  var cornerRadius: Double = 5.0
  override func incrementBy(points: Double = 7.0){
    width += points
    height += points
  }
}

3 Answers

Omar Nunez
Omar Nunez
4,101 Points

You Should init that RoundButton class, because you have a new var "cornerRadius"

init(width:Double,height:Double,cornerRadius:Double){
    self.cornerRadius = cornerRadius
    super.init(width: width, height: height)

Actually a subclass will automatically use its super's designated initialiser if none is provided - so in this case it's not necessary. It's true that if you wanted the cornerRadius to be an argument when instantiating the RoundButton then a new designated initialiser is in order...

Hi Shubham

You can either omit the override keyword (called overloading) or insert an underscore before the argument name. Also you can take advantage of the base class function with the super keyword.

class RoundButton: Button {
    var cornerRadius: Double = 5.0

    override func incrementBy(_ points: Double = 7.0){
        super.incrementBy(points)
    }

   // Or, with overloading...

    func incrementBy(points: Double = 7.0){
        super.incrementBy(points)
    }
}
Omar Nunez
Omar Nunez
4,101 Points

Agree... It will be something like this

// Subclasses and Override    
class RoundButton: Button {
var cornerRadius = 5.0
    init(width:Double,height:Double,cornerRadius:Double){
        self.cornerRadius = cornerRadius
        super.init(width: width, height: height)
    }
    override func incrementBy(_ Points: Double = 7.0) {
        height = height + Points
        width = width + Points
        }
}