Blog

Swift Tip: Type-Safe Initialization Using Storyboards (Part 2)

In last week's Swift Tip, we showed a simple way to configure view controllers by adding a configure method:

								func configure(context: NSManagedObjectContext, recording: Recording) {
    self.context = context
    self.recording = recording
}

							

In our new book, App Architecture, we show an alternative approach. In the MVVM-C implementation, we use Storyboards to lay out the view controllers, but provide static wrapper methods that construct the view controllers with the required parameters:

								extension UIStoryboard {
	func instantiatePlayerNavigationController(with recording: Recording) -> UINavigationController {
		let playerNC = instantiateViewController(withIdentifier: "playerNavigationController") as! UINavigationController
		let playerVC = playerNC.viewControllers[0] as! PlayViewController
		playerVC.viewModel.recording.value = recording
		return playerNC
	}
}

							

Instead of segues, we move the logic into a coordinator class, and manually trigger presentation:

								extension Coordinator: FolderViewControllerDelegate {
	func didSelect(_ recording: Recording) {
        let playerNC = storyboard.instantiatePlayerNavigationController(with: recording)
        splitViewController.showDetailViewController(playerNC, sender: self)
	}
}

							

This makes it even harder to make a mistake when presenting view controllers. Instead of using segues, we can ensure that all parameters are present upon construction.

Read our book App Architecture for a full description of the technique, or watch Swift Talk Episode 5 for a demonstration of a similar technique.


  • Watch the Full Episode

    Architecture

    Connecting View Controllers

    We refactor our code by moving the app's flow from the storyboard into a separate coordinator class. This avoids view controllers having implicit knowledge of their context.

    Episode 5 · July 08, 2016

  • See the Swift Talk Collection

Stay up-to-date with our newsletter or follow us on Twitter .

Back to the Blog

Recent Posts