在尝试调用泛型函数参数时获取错误,swift

时间:2016-07-28 04:29:19

标签: ios swift generics protocols

我的功能是采用符合某种协议的通用类型参数

    // 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)
        }
     }

在另一个类中,我通过调用上面的函数实例化一个视图控制器,如下所示:

let editAssignmentViewController  = storyboard.instantiateViewController(MyTestClass)

然而,xcode给我一个错误如下

 Cannot convert value of type '(MyTestClass).Type' (aka 'MyTestClass') to expected argument type 'UIViewController'

有谁知道我错过了什么以及如何解决此错误

1 个答案:

答案 0 :(得分:1)

我正在收集您的意图是您希望能够执行以下操作:

let controller = storyboard!.instantiateViewController(SomeViewController)

如果这就是你想要做的事情,似乎可以在没有任何协议的情况下完成,只需:

extension UIStoryboard {
    func instantiateViewController<T: UIViewController>(viewController: T.Type) -> T {
        return instantiateViewControllerWithIdentifier(String(T)) as! T
    }
}

我必须承认我更愿意坚持标准

let controller = storyboard!.instantiateViewControllerWithIdentifier("SomeViewController") as! SomeViewController