ios - 尝试调用通用函数参数时出现错误,swift

标签 ios swift generics protocols

我的函数采用符合特定协议(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/

相关文章:

ios - 从 UIImagePickerViewController 给出的路径快速加载图库中的图像?

iphone - 无法设置 UIButton 的标题

iOS 开发者计划

swift - 如何重置 UICollectionVIewCell 的背景颜色

java - 动态类型方法中的奇数类型推断

ios - XCode 6.1 iOS提交

从模拟器关闭应用程序时的 iOS 调试位置监控

ios - Yelp API 业务详情端点

c# - 从字符串实例化泛型

c# - `where T : Delegate` 还是 `where T : MulticastDelegate` ?