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 Object-Oriented Swift Classes in Swift Introduction to Classes

Why this initializer method?

I'm not clear why we are using:

init(x: Int, y: Int) {
        self.position = Point(x: x, y: y)
    }

versus

init(position: Point) {
        self.position = position
    }

Can anyone explain this clearer than the video?

1 Answer

Simon Di Giovanni
Simon Di Giovanni
8,429 Points

Sure!

So first of all , ‘Point’ is a struct. It has two variables, x and y.

To create an instance of Point, you need to assigned values to ‘x’ and ‘y’

So, to initialise this, you need to ask the user to put in values for ‘x’ and ‘y’

Then, the compiler can create an instance of ‘Point’. Now that an instance of ‘Point’ has been been created, it can now be assigned to ‘position’

Think of it this way - if you were the one initializing ‘Point’, how can you type in a struct that has two values? You can’t. So you need to do each one individually (x and y)

If this still doesn’t make sense please let me know!