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 2.0 Complex Data Structures Initializers and Self

zaid
zaid
1,806 Points

Which side of the operator is referring to the global and which side is referring to the local constant

struct Point { let x: Int let y: Int

init(x: Int, y: Int) {
    self.x = x // Does the left side of the operation reference the global or the local constant?
    self.y = y
}

Does it matter which side the constant is at all? Does self. will always refer to global?

2 Answers

Abdullah Althobetey
Abdullah Althobetey
18,216 Points

self.x refers to the x property of the object itself. Where x refers to the argument x of the function. We use self.x = x just to distinguish between the x, the property, and the x, the argument. if the argument were named something else other than x (for example xCord), then we do not need to write self.x because in this case we only have one x which is the property x

init(xCord: Int, yCord: Int) {
    x = xCord
    y = yCord
}

Hope this help.

Damien Watson
Damien Watson
27,419 Points

Always learning, cheers. :)

Damien Watson
Damien Watson
27,419 Points

Hi, its not so much which side, but what you are setting on left or right.

In your example, the left, the 'self' denotes the object you are setting (global for your object) and the right side it what you are setting it to.

I've changed the variable names purely to make it more descriptive (this is not required or necessarily recommended):

init(updateToX: Int, updateToY: Int) {
    self.x = updateToX
    self.y = updateToY
}
zaid
zaid
1,806 Points

This might be a big questions, but I can't wrap my head around the purpose of using init every. Why not just let Xcode handle it?

Damien Watson
Damien Watson
27,419 Points

It depends if the class you're using has it set up the way you need to use it. If the default setting is as required then sure, leave xCode to handle it as per default initialise method.

If you need to customise it in any way or it is a brand new class, then you need to write your own init method. In the case of a new class, xCode doesn't know how to handle it yet as it didn't exist until now. 'init' is the constructor method, tells the class how to build the default instance.

Does this make sense?