Skip to content

Instantly share code, notes, and snippets.

@niazoff
Created October 9, 2018 01:05
Show Gist options
  • Save niazoff/dd1cd7cadb981fd9873f769f8c5c7b06 to your computer and use it in GitHub Desktop.
Save niazoff/dd1cd7cadb981fd9873f769f8c5c7b06 to your computer and use it in GitHub Desktop.
A protocol for creating a view controller from a storyboard with the same name faster.
/// A `UIViewController` that has a matching storyboard file with the same name.
protocol Storyboardable where Self: UIViewController {}
extension Storyboardable {
/// Returns a `UIViewController` instance with the initial view controller of the matching storyboard file in the given bundle.
static func storyboardInstance(bundle: Bundle = Bundle.main) -> Self {
let className = String(describing: Self.self)
let storyboard = UIStoryboard(name: className, bundle: bundle)
if let initialViewController = storyboard.instantiateInitialViewController() as? Self {
return initialViewController
} else { fatalError("Could not instantiate a \(className) instance from the storyboard.") }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment