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