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 trialalex santorineos
4,345 PointsHow 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!
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
47,913 PointsYou'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)
Ron Gootman
24,409 PointsRon Gootman
24,409 PointsThank 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
47,913 PointsMichael Hulet
47,913 PointsCorrect.
init
methods inclass
es are not automatically generated (other than the standard, parameter-lessinit
), so if it's a base class, it has the previously described no-parameterinit
, and if it's a subclass of something, it inherits theinit
method from its superclass (this is all assuming you don't define your owninit
, of course). If you want to set thecornerRadius
property on your instance ofRoundButton
, you'd do so like this:roundButton.cornerRadius = 100 //Or whatever other value you want
alex santorineos
4,345 Pointsalex santorineos
4,345 Pointshttps://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!