Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Enums and Structs Structs and their Methods Initializers

nydia subur
nydia subur
1,672 Points

.self and init

i don't understand why we always need .self when in init..

1 Answer

Martin Wildfeuer
PLUS
Martin Wildfeuer
Courses Plus Student 11,071 Points

You don't. You only have to refer to self if the variable/method name you are referencing is ambiguous. The reason why this is particularly often the case with custom init methods, is that we often use the same names for the (external&internal) parameters as the stored properties. To illustrate that:

struct Person {
    let firstName: String
    let lastName: String
    let age: Int

    init(firstName: String, lastName: String, ageOfPerson: Int) {
        // Within the scope of this init method there are now
        // two firstName and lastName each. Firstly, the ones
        // we pass as parameters, secondly the stored properties 
        // of our struct. (This is also called shadowing)

        // This fails, as the compiler thinks we want to assign the
        // parameter to itself, although it is a constant
        firstName = firstName       

        // Therefore, we have to be more specific
        self.firstName = firstName
        self.lastName = lastName

        // By adding self, the compiler understands that we
        // are referring to the stored property instead of the parameter

        // But what about ageOfPerson? ageOfPerson does not shadow
        // anything, thus age is not ambiguous and we can assign it to
        // the stored property without self
        age = ageOfPerson
   }
}

Hope that clears things up a bit :)