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 Enumerations and Optionals in Swift Introduction to Optionals Initializing Optional Values

Tobias Laursen
Tobias Laursen
5,326 Points

Why do I need the self.?

Hi

I have completed the challenge with the following code.

I had written identical code without the self. on the last four lines, at first, but that wouldn't work.

My question is quite simple, why do I need to include the self. in this case?

optionals.swift
struct Book {
    let title: String
    let author: String
    let price: String?
    let pubDate: String?

    init?(dict: [String : String]) {
        guard let title = dict["title"], let author = dict["author"] else {
        return nil
      }


        self.title = title
      self.author = author
        self.price = dict["price"]
      self.pubDate = dict["pubDate"]

    }

}

1 Answer

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,862 Points

Hi Tobias,

self in this context means the instance's property of that name.

So in your initialiser method you are taking a dictionary with various values as your input. In your guard let statement you are creating two temporary constants called title and author and assigning them values from the dictionary. These temporary constants, being declared in the initialiser will only survive until the end of the initialiser, then they get deallocated.

In order to put the values that are in these temporary constants into the instance-level constants with the same name you tell Swift you are referring to the instance level versions using self. So in the line:

self.title = title

The title on the left of the assignment operator is the instance-level version and the version and the title on the right is the temporary one you just created with method-level scope. By using the assignment operator you are putting the value from the method-level version on the right into the instance-level one on the left.

Hope that clears it up.

Cheers

Alex

Tobias Laursen
Tobias Laursen
5,326 Points

Hi Alex

Thank you, I think that helped me clear things up, for now anyway :)