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 trialNate Camorlinga
1,165 PointsWhy won't this very simple class in swift work?
This is part of the code challenge in the ios beginner course. I don't understand why this wouldn't work. Can someone explain? Thanks!
class Shape {
var numberOfSides: Int
init() {
let someShape = Shape(numberOfSides: 2)
print(numberOfSides)
}
}
1 Answer
andren
28,558 PointsThere are a couple of issues:
You have not added numberOfSides as a parameter to
init
, and have not initialized thenumberOfSides
property.You try to create an instance of the class within the class'
init
method, which is invalid because it would lead to an infinite loop of the object creating instance of itself over and over.
Here is the corrected code with some comments added:
class Shape {
var numberOfSides: Int
init(numberOfSides: Int) { // Add numberOfSides as parameter
self.numberOfSides = numberOfSides // Initalize the numberOfSides property by assigning it the property that is passed in
}
}
let someShape = Shape(numberOfSides: 2) // Create instance of the class outside of the class' definition
If you have any further questions then feel free to ask, I'll try to clarify anything you might be confused about.