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

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


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