Skip to content

Instantly share code, notes, and snippets.

@OksanaFedorchuk
Last active April 23, 2021 13:05
Show Gist options
  • Save OksanaFedorchuk/7b271d2ede25c751855ca4bbce5c5dfb to your computer and use it in GitHub Desktop.
Save OksanaFedorchuk/7b271d2ede25c751855ca4bbce5c5dfb to your computer and use it in GitHub Desktop.
ViewController Extension to instantiate VC, with identifiable protocol to pass storyboard identifiers
import UIKit
protocol StoryboardIdentifiable {
static var storyboardIdentifier: String { get }
}
extension StoryboardIdentifiable where Self: UIViewController {
static var storyboardIdentifier: String {
return String(describing: self)
}
}
extension UIViewController: StoryboardIdentifiable {}
extension UIStoryboard {
enum Storyboard: String {
case main
case another
var filename: String {
return rawValue.capitalized
}
}
convenience init(storyboard: Storyboard, bundle: Bundle? = nil) {
self.init(name: storyboard.filename, bundle: bundle)
}
func instantiateViewController<T: UIViewController>() -> T where T: StoryboardIdentifiable {
guard let viewController = self.instantiateViewController(withIdentifier: T.storyboardIdentifier) as? T else {
fatalError("Couldn't instantiate view controller with identifier \(T.storyboardIdentifier) ")
}
return viewController
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment