如何重用此代码传递 ViewController 名称

How can I Reuse this code Passing a ViewController name

我正在使用 swift 语言编程,我想重用这段代码,将标识符作为字符串传递,将页面作为视图控制器名称传递,但我收到错误 使用未声明的类型'page',我该如何实现?谢谢

func toReuseSession(identifier: String, **page**: UIViewController){
            
    let mainStoryBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
    
    guard let mainVC = mainStoryBoard.instantiateViewController(withIdentifier: identifier) as? **page** else {
        return
    }
    mainVC.modalPresentationStyle = .fullScreen
    present(mainVC, animated: true, completion: nil)
    
}

这是一个可能的泛型解决方案,但您必须在第二个参数中传递静态类型

extension UIViewController {
    
    func toReuseSession<T>(identifier: String, page: T.Type) where T : UIViewController {
        
        let mainStoryBoard = UIStoryboard(name: "Main", bundle: .main)
        
        guard let mainVC = mainStoryBoard.instantiateViewController(withIdentifier: identifier) as? T else {
            return
        }
        mainVC.modalPresentationStyle = .fullScreen
        present(mainVC, animated: true, completion: nil)
    }
}

根据你的功能,你应该声明一个通用类型的 UIViewController 这样你就可以实现你的输出。我已经用正确的语法修改了你的函数,你可以使用它:-

 func toReuseSession<T:UIViewController>(identifier: String, page: T){

    let mainStoryBoard = UIStoryboard(name: "Main", bundle: Bundle.main)

    guard let mainVC = mainStoryBoard.instantiateViewController(withIdentifier: identifier) as? T else {
        return
    }
    mainVC.modalPresentationStyle = .fullScreen
    present(mainVC, animated: true, completion: nil)

}

现在你可以这样调用你的函数了:-

 self.toReuseSession(identifier: "NewPasswordViewController", page: NewPasswordViewController()) 

// “NewPasswordViewController”在我的例子中是在我检查它是否工作时。您可以更改 ViewController 想要显示的内容。