我正在遵循一个设计,其中每个视图控制器都在其自己的情节提要板上进行设计和配置。例如,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