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

iOS

Chris Roberts
Chris Roberts
3,970 Points

What is the point of custom initialisers?

Just completed the custom initialiser video and code challenge. I get how to use them and didn't mind the code challenge too much but I just don't understand the purpose of using one? Could anyone provide an example of when it would be useful to use a custom initialiser? I'm not trying to come off as cynical I'm just genuinely unsure about when to use them. Thanks!

1 Answer

Chris, as you dive deeper into the world of iOS, you will find custom initializers to be a very handy tool. Think about this: you want to create a class for a car, and there are specific variables you want the car to have. For this example, lets just say the car will need a price, color, and number of wheels (it's basic). Instead of setting these important variables after initializing the object, you can do them all in one, using one line of code instead of four:

Car *car1 = [[Car alloc] initWithPrice:10000 color:[UIColor redColor] wheels:4]; 

//Instead of: 
Car *car1 = [[Car alloc] init]; 
car1.price = 10000;
car1.color = [UIColor redColor];
car1.wheels = 4;

Here is the swift version:

var car1 = Car(price: 10000, color: UIColor.red, wheels: 4)
    //Instead of: 
var car1 = Car()
car1.price = 10000
car1.color = UIColor.red
car1.wheels = 4

If you have any further questions, don't hesitate to ask!

Chris Roberts
Chris Roberts
3,970 Points

Ahhh ok, that makes a lot more sense now. I'm gonna rewatch the last few videos to see if i can understand it any better this time round. Thanks for the help :)