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 trialBen Masel
2,004 PointsWhats And Instance Again? Also Help Me With This CC!
I really don't get the meaning of an Instance and an Initializer method! Please also try to help me complete this CC!
class Shape {
var numberOfSides: Int
}
2 Answers
Jason Cornwall
9,645 PointsYou can think of a class as a blueprint for building a house, and an object (or instance) as the house that you build using the blueprint. An instance initializer method is a function that all classes have in order to allow you to assign values to a stored property once you decide to create the object. For example:
class House {
let sides: Int
let location: String
}
This is a class, or the blueprint. But if we wanted to create a house, we would have no way of assigning it values. So we use an initializer like this:
class House {
let sides: Int
let location: String
init(sides: Int, location: String) {
self.sides = sides
self.location = location
}
}
What this does is it now allows us to assign values to a house should we decide to create one. Now we can do that like this:
let myHouse = House(sides: 4, location: "suburbs")
let friendsHouse = House(sides: 6, location: "city")
We now just created 2 houses, or house objects, with 2 different properties each. And we used initializer methods to do it. I hope that helped!
Jason Cornwall
9,645 PointsYou were really close! Remember that when you say self.numberOfSides, you're referring to the stored property in the class. The value that you're assigning to it should be the parameter of your init function since thats how you will assign values to your objects. Once you do that, it should look like this:
class Shape {
var numberOfSides: Int
init(sides: Int) {
self.numberOfSides = sides
}
}
Also, remember that when you're going to create an object from your class, you have to do it outside of the class itself. You have the right idea though. Good luck!
Ben Masel
2,004 PointsSorry, it's still not working! I think i have a code challenge problem because every time i try to compile and someone helps me, it says can not compile!
Ben Masel
2,004 PointsBen Masel
2,004 PointsThanks So Much!
Ben Masel
2,004 PointsBen Masel
2,004 PointsActually... I still can't get my CC to compile! But i do understand the meanings of initializer methods and instances! This is what I've done know:
Ben Masel
2,004 PointsBen Masel
2,004 PointsI think i made a nooby mistake!