Briahas
8/21/2017 - 7:55 AM

init from Storyboard

init from Storyboard

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
    }
}