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 trial

iOS Intermediate Swift 2 Object Initialization Initializer Delegation

Kevin Gutowski
Kevin Gutowski
4,082 Points

Not quite sure I follow the importance of multiple inits with regard to creating an instance of Rectangle?

From what I gather, all we just did was design Rectangle so that we can create an instance of it in one of three ways? Why is this flexibility important? Why can't we get away with just creating one init?

Kevin Gutowski
Kevin Gutowski
4,082 Points

Thanks for the feedback! I definitely understand how its useful to have multiple inits now! That's pretty cool.

2 Answers

Daniel Cohen
Daniel Cohen
5,785 Points

If we create multiple init methods then we can initialize the struct in different ways depending on the information we have at hand. If we already have the origin and size, we can use the first method init(origin: Point, size: Size). If we only have the x and y coordinates of the origin, and the width and height of the rectangle, but we don't have the Point and Size instances for these, then we would use the second init method init(x: Int, y: Int, width: Int, height: Int) . If we have the center and the size, instead of the origin and the size, then we use the third init method init(center: Point, size: Size) .

I assume that this will be useful so that in our app we have flexibility to choose the init method that suits our input data, without having to write more code later to work out for example where the origin of the rectangle will be if we know where the center is.

Peter Michiels
Peter Michiels
3,501 Points

Hi Kevin

As a real-world example: Several CAD applications offer the possibility to draw a rectangle in multiple ways, depending on what information you have and how you want to draw your rectangle.

alt text

Gr Peter