代码之家  ›  专栏  ›  技术社区  ›  SwiftyJD

创建一个以uiviewcontroller作为参数的函数

  •  -1
  • SwiftyJD  · 技术社区  · 7 年前

    我试图创建一个以uiviewcontroller为函数的函数。原因是可以传递多个自定义viewcontrollers。下面是我的当前函数,它可以工作,但使用switch语句和枚举:

    enum controllerTypes {
        case First, Second
    }
    
    extension UIViewController {
    
        func presentViewController(storyBoardName: String, storyBoardIdentifier: String, controllerType: controllerTypes, completion:(() -> Void)?) {
    
            switch controllerType {
    
            case .First:
                let firstVC = UIStoryboard(name: storyBoardName, bundle: nil).instantiateViewController(withIdentifier: storyBoardIdentifier) as? FirstViewController
                if let firVC = firstVC {
                    self.present(firVC, animated: true, completion: nil)
                }
            case .Second:
                let secondVC = UIStoryboard(name: storyBoardName, bundle: nil).instantiateViewController(withIdentifier: storyBoardIdentifier) as? SecondViewController
                if let secVC = secondVC {
                    self.present(secVC, animated: true, completion: nil)
                }
            }
            completion?()
        }
    }
    

    我不想为参数传递'controllerTypes'枚举,而是要传递任何类型的uiviewcontroller,当我尝试执行此操作时,出现以下错误:

            func presentViewController(storyBoardName: String, storyBoardIdentifier: String, controllerType: UIViewController, completion:(() -> Void)?) {
                let sampleVC = UIStoryboard(name: storyBoardName, bundle: nil).instantiateViewController(withIdentifier: storyBoardIdentifier) as? controllerType//error - use of undeclared type 'controllerType'
                if let samVC = sampleVC {
                    self.present(samVC, animated: true, completion: nil)
                }
    }
    

    你知道这样做是否可行吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   dan    7 年前

    必须使函数成为泛型,然后强制转换为泛型参数类型:

    extension UIViewController {
        func presentViewController<T: UIViewController>(storyBoardName: String, storyBoardIdentifier: String, controllerType: T.Type, completion:(() -> Void)?) {
            let sampleVC = UIStoryboard(name: storyBoardName, bundle: nil).instantiateViewController(withIdentifier: storyBoardIdentifier) as? T
            if let samVC = sampleVC {
                self.present(samVC, animated: true, completion: completion)
            }
        }
    }