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 Build an Interactive Story App with Swift Creating a Story Structure of a Page

Justin Comstock
Justin Comstock
122 Points

I don't really understand the init part.

class Page { let story: Story typealias Choice = (title: String, page: Page)

var firstChoice: Choice?
var secondChoice: Choice?

init(story: Story) {
    self.story = story
}

}

This seems meta to have story = story and so forth and I can't wrap my head around it.

1 Answer

andren
andren
28,499 Points

The important thing to understand is that self.story and story do not refer to the same variable. The self.story variable points to the story field that is defined at the top of the Page class. While story refers to the parameter of the init method:

class Page { 
    let story: Story typealias // This is self.story
    Choice = (title: String, page: Page)

    var firstChoice: Choice?
    var secondChoice: Choice?

    init(story: Story) { // This is story (within the init method)
       self.story = story
    }
}

So self.story = story is actually telling Swift to take the story field that is defined in the Page object and set it equal to the story argument that is passed in to the init method. This is needed because the story parameter will only exist within the init method, it won't be accessible outside it. This pattern of creating an attribute and then assigning it a value that is passed in though the init method is pretty common in OOP languages.