我正在尝试创建一个将UIViewController作为函数的函数。原因是有多个自定义视图控制器可以传递。这是我当前的函数,它可以使用switch语句和enum:
enum controllerTypes {
case First, Second
}
extension UIViewController {
func presentViewController(storyBoardName: String, storyBoardIdentifier: String, controllerType: controllerTypes, completion:(() -> Void)?) {
switch controllerType {
case .First:
let firstVC = UIStoryboard(name: storyBoardName, bundle: nil).instantiateViewController(withIdentifier: storyBoardIdentifier) as? FirstViewController
if let firVC = firstVC {
self.present(firVC, animated: true, completion: nil)
}
case .Second:
let secondVC = UIStoryboard(name: storyBoardName, bundle: nil).instantiateViewController(withIdentifier: storyBoardIdentifier) as? SecondViewController
if let secVC = secondVC {
self.present(secVC, animated: true, completion: nil)
}
}
completion?()
}
}
而不是传递'controllerTypes'枚举的参数我想传递任何类型的UIViewController,当我尝试这样做时,我得到以下错误:
func presentViewController(storyBoardName: String, storyBoardIdentifier: String, controllerType: UIViewController, completion:(() -> Void)?) {
let sampleVC = UIStoryboard(name: storyBoardName, bundle: nil).instantiateViewController(withIdentifier: storyBoardIdentifier) as? controllerType//error - use of undeclared type 'controllerType'
if let samVC = sampleVC {
self.present(samVC, animated: true, completion: nil)
}
}
是否可以这样做?
答案 0 :(得分:1)
您必须使您的函数通用,然后转换为通用参数类型:
extension UIViewController {
func presentViewController<T: UIViewController>(storyBoardName: String, storyBoardIdentifier: String, controllerType: T.Type, completion:(() -> Void)?) {
let sampleVC = UIStoryboard(name: storyBoardName, bundle: nil).instantiateViewController(withIdentifier: storyBoardIdentifier) as? T
if let samVC = sampleVC {
self.present(samVC, animated: true, completion: completion)
}
}
}