Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Param is 'out of scope' in its own function

My UITabBarController has a method to switch to a tab of a certain View Controller type. The method takes a parameter for this VC type called newVC. Its type is UIViewController.Type. The method finds a tab with that type, and switches to it.

The method works fine when the newVC type is hard-coded inside the method. But when I put it as a variable, XCode complains that the newVC param isn’t available inside the method.

For the love of god, why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

func animateToVC(_ newVC: UIViewController.Type){
      guard let VCs = viewControllers else { return }

      for (listIndex, vc) in VCs.enumerated(){
         guard let navController = vc as? CustomNavBarController,
               navController.rootViewController is newVC else { continue } --> "Cannot find type 'newVC' in scope"

         animateToView(atTabIndex: listIndex)
         selectedIndex = listIndex
      }
   }

>Solution :

You cannot use a variable with the is keyword in Swift for type checking. However, you can make the method generic and use the generic type parameter instead.

func animateToVC<ViewControllerType: UIViewController>(_ newVC: ViewControllerType.Type) {
    guard let VCs = viewControllers else { return }

    for (listIndex, vc) in VCs.enumerated(){
        guard let navController = vc as? CustomNavBarController,
              navController.rootViewController is ViewControllerType else { continue }

        animateToView(atTabIndex: listIndex)
        selectedIndex = listIndex
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading