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 trialaren polat
883 Pointsinit and class
I don't think i understood the init method right could someone give me explanation of what it does and why we need to use them. I watched the video a couple of times but i dont seem to understand it.
thank you
// Enter your code below
class Shape {
var numberOfSides: Int
init() {
self.numberOfSides = numberOfSides
}
}
let someShape = numberOfSides
1 Answer
Brandon Mahoney
iOS Development with Swift Techdegree Graduate 30,149 PointsSo init is used to initialize the object i.e. assign it, its initial value. Below are two answers that are both accepted by the challenge. The first assigns a pre determined number of sides and the second uses a parameter in the init method which will be assigned later.
1 -
class Shape {
var numberOfSides: Int
init() {
self.numberOfSides = 4
}
}
let someShape = Shape()
2 -
class Shape {
var numberOfSides: Int
init(numberOfSides: Int) {
self.numberOfSides = numberOfSides
}
}
let someShape = Shape(numberOfSides: 4)