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 trialmattcleary2
19,953 PointsAm I close?
Hey guys,
I hope I'm close on this. I've gone through all the swift lessons again after getting stuck here last time.
I THINK I understand initialiser though.
I'm not sure what I'm doing wrong however.
Not sure when to assign values or when/if I should type return etc.
Any help would be much appreciated please.
// Enter your code below
class Shape{
var numberOfSides = Int()
init(sides:Int) {
self.numberOfSides = sides
}
}
let someShape = sides(4)
1 Answer
Michael Jones
Python Development Techdegree Graduate 38,554 PointsHi Matt,
So what you've done is created a class named 'Shape', inside this 'Shape' class you have creative a variable called 'numberOfSides' which is of type 'Int' (this variable has no value assigned to it).
And for all classes you have to initialize a value towards it, which you've done.
Then outside of the scope of the 'Shape' class, you have created a constant called 'someShape' which is pointing to the class you've called 'Shape' and your assigning a value to the variable called 'numberOfSides' which you have said is 4.
class Shape {
var numberOfSides: Int
init(numberOfSides: Int){
self.numberOfSides = numberOfSides
}
}
let someShape = Shape(numberOfSides: 4)
Does this make more sense?
Happy coding!!
Michael J
J.D. Sandifer
18,813 PointsAlso, to answer Matt's other question, the parentheses after Int aren't necessary.
For what it's worth, to pass the code challenge you also don't need to take an argument for init(). I was able to complete it by setting numberOfSides to a specific value (1 in my case).
Although it might not be useful for whatever app is using the class, it illustrates that it's not necessary to create the class - just assigning some value to the variable is enough. (Especially since numberOfSides is a variable...it's always good to check your assumptions in programming.)
mattcleary2
19,953 Pointsmattcleary2
19,953 PointsOkay, so I did it.
But I don't really understand WHAT I did and why I needed to so it. I still don't understand the use in the initializer.
Why wouldn't THIS work?
Why isn't that more logical? And why the empty parenthesis after INT?
thank you guys