Creating a generic UViewController initialiser

generics, ios, swift, swift-protocols, uiviewcontroller

Solution

I use this extension:

extension UIViewController
{
    class func instantiateFromStoryboard(_ name: String = "Main") -> Self
    {
        return instantiateFromStoryboardHelper(name)
    }

    fileprivate class func instantiateFromStoryboardHelper<T>(_ name: String) -> T
    {
        let storyboard = UIStoryboard(name: name, bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: String(describing: self)) as! T
        return controller
    }
}

Usage:

let controller = MyViewController.instantiateFromStoryboard()

Problem

I'm trying to create a `UIViewController` extension that I can use to initialise new instances. For each view controller in my project I have a corresponding storyboard. i.e. ``` EditSomethingViewController.swift EditSomethingViewController.storyboard ``` This is what I have so far: ``` extension UIViewController { static func initalize() -> UIViewController? { let name = String(self) let storyboard = UIStoryboard(name: name, bundle: nil) return storyboard.instantiateInitialViewController() } } ``` However this means that when I use it, I still have to cast the response. i.e. ``` if let viewController = EditSomethingViewController.initalize() as? EditSomethingViewController { // do something with view controller here } ``` Is it possible to create the extension in such a way that means I don't have to cast the response? p.s. Working on an old project written in Swift 2.3 so would appreciate answers that are supported.

Original source