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!
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 trial
meitav asulin1,123 Points
I have few questions about methods
- methods are actually function inside class or structure?
- instance method is actually when I use it of the class or the structure?
- initializers- why I need them?
- When I use initializer on subclass am I always need to write super.init and what is it mean?
Thank you and have a nice day
Marlon Henry6,885 Points
1- methods are actually function inside class or structure?
Answer: Methods are functions, they can be inside a class, a struct, enum, shoot even a computed variable is basically a method.
2- instance method is actually when I use it of the class or the structure?
Answer: A instance method is used on a instance of the class, which is different then a class method...think about all those string methods out there, when you make a instance of a string you can call one of those on them.
3-initializers- why I need them?
Answer: They make things easier, they help set up values for objects when you initialize the object or a instance of the class instead of initializing it to nil and then having to go later on in the code and add values.
4- When I use initializer on subclass am I always need to write super.init and what is it mean?
Answer: When you call super.init you are calling the super class to the class you are subclassing from. You do this to initial the class and all it's methods within it so you have access to them if you choose to use them.
Greg Kaleka39,020 Points
Greg Kaleka39,020 Points
Good answers - I'll just throw in some additional info for class/instance method:
Once you get a bit more programming under your belt, Meitav, you'll understand when it makes sense to make a method an instance method or a class (or other structure) method. For example, let's say you create a class
Math, and it has all kinds of fun math methods like
max(). It probably makes sense to have those as class methods. There's not a great reason to create an instance of Math in order to simply calculate the square root of a number. On the other hand, if you had a class like Car, you're not going to have many class methods (other than init), since a Car can't really do anything until you actually have one. Car.drive() doesn't really make sense. You'd have to create an instance like myCar, and then drive it with myCar.drive() - that's an instance method.
Hope that's helpful!