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 the User Interface Programmatically Continuing Our Story

Amanda Augusto
Amanda Augusto
10,217 Points

Unnecessary duplicated code

I understand that you need to provide 2 separated functions with no params for the choices button events. But instead of this:

func loadFirstChoice() {
    if let page = page, let firstChoice = page.firstChoice {
        let nextPage = firstChoice.page
        let nextPageController = PageController(page: nextPage)

        navigationController?.pushViewController(nextPageController, animated: true)
    }
}

func loadSecondChoice() {
    if let page = page, let secondChoice = page.secondChoice {
        let nextPage = secondChoice.page
        let nextPageController = PageController(page: nextPage)

        navigationController?.pushViewController(nextPageController, animated: true)
    }
}

Wouldn't be better to do something like this:

func loadFirstChoice() {
    guard let page = page else { return }
    goToPage(for: page.firstChoice)
}

func loadSecondChoice() {
    guard let page = page else { return }
    goToPage(for: page.secondChoice)
}

func goToPage(for choice: Page.Choice?) {
    guard let choice = choice else { return }

    let nextPage = choice.page
    let nextPageController = PageController(page: nextPage)

    navigationController?.pushViewController(nextPageController, animated: true)
}

There is no duplication on the code, and the 2 functions calls stays the same.