创建一个通用的UViewController初始化程序

Oll*_*lie 5 generics uiviewcontroller ios swift swift-protocols

我正在尝试创建UIViewController可用于初始化新实例的扩展。对于项目中的每个视图控制器,我都有一个相应的情节提要。

EditSomethingViewController.swift
EditSomethingViewController.storyboard
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止的内容:

extension UIViewController {

    static func initalize() -> UIViewController? {
        let name = String(self)

        let storyboard = UIStoryboard(name: name, bundle: nil)

        return storyboard.instantiateInitialViewController()
    }

}
Run Code Online (Sandbox Code Playgroud)

但是,这意味着当我使用它时,我仍然必须强制转换响应。

if let viewController = EditSomethingViewController.initalize() as? EditSomethingViewController {
     // do something with view controller here  
}
Run Code Online (Sandbox Code Playgroud)

是否可以通过这种方式创建扩展名,这意味着我不必强制响应?

ps在一个用Swift 2.3编写的旧项目上工作,将不胜感激所支持的答案。

Chi*_*buZ 8

我使用这个扩展:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

let controller = MyViewController.instantiateFromStoryboard()
Run Code Online (Sandbox Code Playgroud)