Reputation: 61880
I am trying to define generic function to access any controller from UITabBarController and return it.
protocol TabBarRoutable {
func select<T: UIViewController>(type: T.Type, from context: UIViewController?) -> T?
}
extension TabBarRoutable {
func select<T: UIViewController>(type: T.Type, from context: UIViewController?) -> T? {
return context?.tabBarController?.viewControllers?.first(where: { ($0 as? UINavigationController)?.viewControllers.first is T })
}
}
Upvotes: 0
Views: 143
Reputation: 15035
UINavigationController)?.viewControllers.first
is always a UIViewController
.
Return UIViewController?
instead of T?
func select<T: UIViewController>(type: T.Type, from context: UIViewController?) -> UIViewController? {
return context?.tabBarController?.viewControllers?.first(where: { ($0 as? UINavigationController)?.viewControllers.first is T})
}
Upvotes: 1
Reputation: 20379
This should work
extension TabBarRoutable {
func select<T: UIViewController>(type: T.Type, from context: UIViewController?) -> T? {
return context?.tabBarController?.viewControllers?.first(where: { ($0 as? UINavigationController)?.viewControllers.first is T }) as? T
}
}
I think error shown by compiler is bit misleading, real issue is I guess compiler couldnt figure out the return type of the expression
Upvotes: 2