参数“超出范围”;在它自己的功能中

发布于 2025-01-14 22:37:14 字数 682 浏览 0 评论 0原文

我的 UITabBarController 有一个方法可以切换到某种视图控制器类型的选项卡。该方法采用一个名为 newVC 的 VC 类型参数。它的类型是 UIViewController.Type。该方法找到具有该类型的选项卡,然后切换到它。

当 newVC 类型被硬编码在方法内部时,该方法可以正常工作。但是当我将它作为变量时,XCode 抱怨 newVC 参数在方法内部不可用。

看在上帝的份上,为什么?

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

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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情绪少女 2025-01-21 22:37:14

您不能在 Swift 中使用带有 is 关键字的变量进行类型检查。但是,您可以使该方法成为泛型并使用泛型类型参数。

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

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
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文