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 trialK Jo
7,283 PointsWhen and why do we use self?
You mention that we can add self. before firstName and lastName in the return line, but we do not necessarily need this. Can you explain this in more detail? I believe I understand what self represents, as well as the syntax for using it, but I don't fully understand why it is used. When I take the self. syntax out of the the return line or out of the init lines, the outputs do not appear to change?
1 Answer
Stone Preston
42,016 Pointsit is not necessary to use self most of the time. It is necessary, however, when you have a parameter or other variable with the same name as the property. you must use self to distinguish the property from the parameter:
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
you can see that it would not really work if you did not use self
init(firstName: String, lastName: String) {
//is this referring to the property or the parameter?
firstName = firstName
lastName = lastName
}
from the Swift eBook:
In practice, you donβt need to write self in your code very often. If you donβt explicitly write self, Swift assumes that you are referring to a property or method of the current instance whenever you use a known property or method name within a method
The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way. You use the self property to distinguish between the parameter name and the property name.
really the only time you need to use self is when you have to clear up an ambiguity like the one above, or when you are referencing properties inside closures.
most of the time the parameters of the init method use the same name of the properties, so you will self used a lot in initializers for this reason.