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
Jon Schenck
2,028 PointsWhat do the self. statements mean? In other words why are they used? I am just trying to understand them more.
???
1 Answer
Enrique Munguía
14,311 PointsThe self keyword is used to reference members (i.e properties, methods, etc) of the current class, struct or enum. One common use case is within initializers, in this example we have an structure that represents a two dimensional point. The properties are called x and y, usually the arguments of the init method are called the same, in order to avoid ambiguity during the assignment, the properties are prepended with self.. If the arguments were called differently there would no need to use self.
struct Point {
let x: Int;
let y: Int;
init(x: Int, y: Int) {
self.x = x;
self.y = y;
}
}
There are some cases where the use of self is obligatory for example when a closure is differently properties or methods of a class, if you don't include the sel.f you get a compiler error.