ios - 无法推断通用参数 'T'

标签 ios swift generics

我正在重构我的代码并添加对 Swift 泛型 的支持。我遇到了编译器错误。我的代码是:

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

编译顺利。然后,稍后,当我尝试使 View Controller 出列时:

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

我收到一个错误:

Generic parameter 'T' could not be inferred

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

最佳答案

在调用返回泛型类型的泛型函数时,如果未指定要分配给的变量的类型或将调用强制转换为函数,则无法推断类型。你可以这样做:

let viewController: SomeViewController = self.dequeueReusableViewController()

let viewController = self.dequeueReusableViewController() as SomeViewController

我会推荐第一个选项,除非需要第二个选项(例如需要分配给一个可选的)。

关于ios - 无法推断通用参数 'T',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35157253/

相关文章:

ios - Firebase 存储错误

ios - TableView/Screen 的 AutoLayout UITableViewCell 高度倍数

java - 通用方法无法正确识别类型

android - 智能手机和桌面应用程序通信技术和跨平台框​​架

ios - 所有事件的手势识别器

ios - Swift 3.0 map 返回到以前的 MapView

ios - 试图将数组传递给 swift 函数

ios - 当 NSNotificationCenter 是两个 View Controller 时,在 applicationDidEnterBackground 中调用了两次?

java - 在它的抽象父类(super class)中使用子类的泛型类型?

c - 如何在c中初始化泛型函数