无法推断通用参数"T" [英] Generic parameter 'T' could not be inferred

查看:66
本文介绍了无法推断通用参数"T"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构代码,并添加了对Swift 泛型的支持.我陷入了编译器错误.我的代码是:

I'm refactoring my code and adding support for Swift generics. I'm stuck with a compiler error. My code is:

func dequeueReusableViewController<T: UIViewController where T: Reusable>() -> T {
        // Try to fetch view controller from the reuse queue.
        if !self.viewControllerReuseQueue.isEmpty {
            return self.viewControllerReuseQueue.popFirst()! as! T
        }

        // Ask delegate to instantiate a new view controller.
        return delegate!.reusableViewControllerForPageViewController(self)
}

这可以顺利编译.然后,稍后,当我尝试使视图控制器出队时:

This compiles smoothly. Then, later, when I try to dequeue a view controller:

// Get view controller from the reuse queue.
let viewController: UIViewController = self.dequeueReusableViewController()

我遇到错误:

无法推断出通用参数'T'

Generic parameter 'T' could not be inferred

我该如何解决?我在SO上检查了类似的问题,但没有一个描述我的情况.

How can I solve this? I checked similar questions on SO but none of them describes my case.

推荐答案

在调用不返回您要分配给变量的类型或将调用强制转换为泛型的泛型函数时,无法推断类型.您可以这样做:

The type cannot be inferred when calling a generic function returning a generic type without specifying the type of the variable you are assigning to or casting the call to the function. You can do:

let viewController: SomeViewController = self.dequeueReusableViewController()

let viewController = self.dequeueReusableViewController() as SomeViewController

除非需要第二个选项,否则我建议第一个选项(例如,需要分配给可选选项).

I would recommend the first option unless the second is required (needing to assign to an optional for example).

这篇关于无法推断通用参数"T"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆