我有一个带有通用函数的协议,该协议返回通用ViewController。迫使我在默认实现中添加类型约束检查。
protocol RouterViewController {
func getViewController<T: UIViewController>(_ name: Storyboard) -> T
}
extension RouterViewController {
func getViewController<T>(_ name: Storyboard) -> T where T: UIViewController {
let storyBoard = UIStoryboard.init(storyboard: name)
return storyBoard.instantiateViewController()
}
}
在没有泛型的情况下我可以做的同一示例
struct RouterViewController {
static func getViewController(_ name: Storyboard) -> UIViewController {
let storyBoard = UIStoryboard.init(storyboard: name)
return storyBoard.instantiateViewController()
}
}
我有一系列问题
func<SignIn>() -> T
答案 0 :(得分:0)
如果您在协议声明/扩展中进行小的更改,您将获得所需的功能:
protocol RouterViewController {
func getViewController<T: UIViewController>(_ viewControllerType: T.Type, _ name: Storyboard) -> T
}
extension RouterViewController {
func getViewController<T>(_ viewControllerType: T.Type, _ name: Storyboard) -> T where T: UIViewController {
let storyBoard = UIStoryboard.init(storyboard: name)
let identifier = String(describing: T.self) // Let's say view controller's storyboard identifier is same as class name
return storyBoard.instantiateViewController(withIdentifier: identifier) as! T
}
}
用法:
struct TestStruct: RouterViewController {
}
TestStruct().getViewController(TestViewController.self, #YourStoryboardObject)
有关视图控制器和情节提要的更多信息,请检查:Swift protocol extension