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

Initialising within a struct

I just wanted more information when initialising within a struct and the use of self.

struct Contact {
    let firstName: String
    let lastName: String
    var type: String

    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
        self.type = "Friend"
    }
}

Here, when referencing self, we're talking about whatever instance it is that is being instantiated, right? For example:

var person = Contact(...)

So here, self within the struct is referring to person and therefore when assigning values to the parameters, we'd be giving values to those properties of the struct, albeit an instance of the struct, correct?

1 Answer

Patrick Cooney
Patrick Cooney
12,216 Points

Sounds like you have a pretty good grasp of the concept.

Self refers to the, for lack of a better term, calling instance. So as you said if we have

var person = Contact()

and

var animal = Contact()

they will always have the same properties but the values for those properties will be different. Changing the values in person will not change the values in animal and vice versa.

This makes sense. I just wanted to make sure that I had grasped it correctly. I kind of had a feeling I was right but I certainly didn't want to go ahead and assume that I was without checking first otherwise I'd be thinking one thing when it might have been another. :)