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 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,558 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.