Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61880

Cannot call value of non-function type of UIViewController when using generic types

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

enter image description here

Upvotes: 0

Views: 143

Answers (2)

mahan
mahan

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

Sandeep Bhandari
Sandeep Bhandari

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

Related Questions