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/

相关文章:

swift - 在数组中使用 PAT 存储通用结构的一些问题

generics - StringDictionary 与 Dictionary<string, string>

c# - 带有委托(delegate)参数的通用方法

c# - 异常 : Application initializing document picker is missing the iCloud entitlement. 是否设置了 com.apple.developer.icloud-container-identifiers?

iOS11自定义导航栏高度

iphone - 尝试将数组数据保存/加载到 Plist

iOS 本地化搞乱了 UI

ios - 如何通过 UIViewController(Swift,iOS 9)检测屏幕事件

ios - 为 iOS 构建时,开发团队没有出现错误

image - 以编程方式将图像保存到 Swift 中的 xcassets