我的函数采用符合特定协议(protocol)的泛型类型参数
// This is my function
func instantiateViewController<T: ViewControllerIdentifier>(viewController: UIViewController) -> T
{
let controller = instantiateViewControllerWithIdentifier(viewController.identifier) as! T
return controller
}
// This is an extension of my protocol
extension ViewControllerIdentifier where Self: UIViewController
{
var identifier: String
{
return String(self)
}
}
在另一个类中,我通过调用上面的函数来实例化一个 View Controller ,如下所示:
let editAssignmentViewController = storyboard.instantiateViewController(MyTestClass)
但是,xcode 给我如下错误
Cannot convert value of type '(MyTestClass).Type' (aka 'MyTestClass') to expected argument type 'UIViewController'
有谁知道我遗漏了什么以及如何解决这个错误
最佳答案
我了解到您的意图是希望能够执行以下操作:
let controller = storyboard!.instantiateViewController(SomeViewController)
如果那是你想要做的,似乎它可以在没有任何协议(protocol)的情况下完成,只需:
extension UIStoryboard {
func instantiateViewController<T: UIViewController>(viewController: T.Type) -> T {
return instantiateViewControllerWithIdentifier(String(T)) as! T
}
}
我必须承认我更愿意坚持标准
let controller = storyboard!.instantiateViewControllerWithIdentifier("SomeViewController") as! SomeViewController
关于ios - 尝试调用通用函数参数时出现错误,swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38627121/