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