Last active
April 23, 2021 13:05
-
-
Save OksanaFedorchuk/7b271d2ede25c751855ca4bbce5c5dfb to your computer and use it in GitHub Desktop.
ViewController Extension to instantiate VC, with identifiable protocol to pass storyboard identifiers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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