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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With