Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic parameter 'T' could not be inferred

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

I'm getting an error:

Generic parameter 'T' could not be inferred

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

like image 895
Rafa de King Avatar asked Mar 14 '23 10:03

Rafa de King


1 Answers

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

or

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

like image 148
Joe Avatar answered Mar 23 '23 02:03

Joe