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 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 :)