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 What is Inheritance?

How to make an instance

I am trying to make an instance of the class RoundButton.

I feel I did it correctly but is says I am wrong. Please Help!

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

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


class RoundButton: Button {
var cornerRadius = 5.0

}

let rounded = RoundButton

1 Answer

Michael Hulet
Michael Hulet
47,913 Points

You're close. You know how you create an instance of a struct? classes in Swift are exactly the same way. However, in this instance, because RoundButton doesn't have its own initializer defined, you'll use that of its superclass (the class it inherits from), Button, so in order to create an instance, it'd look like this:

let roundButton = RoundButton(width: 5, height: 5)

Thank you for your answer Michael!

I got a question:

I get why the "Button" parameters are added (width:someDouble, height:someDouble). But we also added the "cornerRadius" parameter to the RoundButton Class. So why is it not included when creating that instance? sort of RoundButton(width:someDouble, height:someDouble, cornerRadius:someDouble) Is it because the "cornerRadius" is not included in the init?

Michael Hulet
Michael Hulet
47,913 Points

Correct. init methods in classes are not automatically generated (other than the standard, parameter-less init), so if it's a base class, it has the previously described no-parameter init, and if it's a subclass of something, it inherits the init method from its superclass (this is all assuming you don't define your own init, of course). If you want to set the cornerRadius property on your instance of RoundButton, you'd do so like this:

roundButton.cornerRadius = 100 //Or whatever other value you want

https://teamtreehouse.com/forum/core-location-framework-swift

can you take a look at the question I've posted and try to help me? Thank you very much!