Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save victor-pavlychko/c03198dbbd9d19286bd47498fd416b10 to your computer and use it in GitHub Desktop.
Save victor-pavlychko/c03198dbbd9d19286bd47498fd416b10 to your computer and use it in GitHub Desktop.
private func dynamicCast<T>(_ object: Any, as: T.Type) -> T? {
return object as? T
}
public extension UIViewController {
public static func makeWithStoryboard(_ name: String? = nil, bundle: Bundle? = nil) -> Self {
let name = name ?? String(describing: self).components(separatedBy: ".").last!
let bundle = bundle ?? Bundle(for: self)
guard bundle.url(forResource: name, withExtension: "storyboardc") != nil else {
fatalError("Can't find storyboard named `\(name)` in bundle `\(bundle)`.")
}
let storyboard = UIStoryboard(name: name, bundle: bundle)
guard let initialViewController = storyboard.instantiateInitialViewController() else {
fatalError("No initial view controller defined in storyboard `\(name)`, bundle `\(bundle)`.")
}
guard let resultViewController = dynamicCast(initialViewController, as: self) else {
fatalError("Wrong initial view controller found in storyboard `\(name)`, bundle `\(bundle)`: expected `\(self)`, found `\(type(of: initialViewController))`.")
}
return resultViewController
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment