返回类动态类型的静态函数

时间:2018-08-12 13:00:26

标签: swift

我正在遵循一个设计,其中每个视图控制器都在其自己的情节提要板上进行设计和配置。例如,MyViewController将容纳在MyViewController.storyboard中,并分配标识符MyViewController。这种一致的命名方式使我可以为UIViewController编写一个方便的扩展名:

extension UIViewController {
    static func fromStoryboard(_ storyboard: UIStoryboard? = nil, identifier: String? = nil) -> UIViewController {
        let className  = NSStringFromClass(self).components(separatedBy: ".").last!
        let storyboard = storyboard ?? UIStoryboard(name: className, bundle: nil)
        let identifier = identifier ?? className

        return storyboard.instantiateViewController(withIdentifier: identifier)
    }
}

每当我需要控制器时,我都可以这样称呼它:

let vc = MyViewController.fromStoryboard() as! MyViewController

我的问题是:如何更改功能,以便可以删除as!类型的转换,并且仍然具有vc类型的MyViewController?换句话说,我要做的是:

let vcA = ViewControllerA.fromStoryboard()  // vcA is of type ViewControllerA
let vcB = ViewControllerB.fromStoryboard()  // vcB is of type ViewControllerB

0 个答案:

没有答案