如何将类型作为 func 参数传递?

How to pass type as func argument?

当试图描述路由程序以使 VC 更精简时,我遇到了一个问题。将类型作为 func 参数传递时出现编译错误

Cannot find type 'destinationType' in scope

在下面的代码中。请看看并解释我做错了什么。

extension MainViewController {
    
    func route<T: UIViewController>(to destinationType: T.Type) {
        let identifier = String(describing: destinationType)
        guard let destinationViewController = self.storyboard?.instantiateViewController(identifier: identifier) as? destinationType else {
            return
        }
        present(destinationViewController, animated: true)
    }
    
}

您的代码中没有任何内容依赖于故事板中的视图控制器的类型。因此,您不需要类型、泛型或任何其他装备。您所需要的只是标识符,您可以说“获取该视图控制器并显示它”:

extension UIViewController {
    func route(to identifier: String) {
        guard let destinationViewController = self.storyboard?.instantiateViewController(identifier: identifier) else { return }
        present(destinationViewController, animated: true)
    }
}

但是,如果您坚持泛型和强制转换,您要查找的类型就不是 destinationType(这是元类型,根本不是类型)— 它是 T

extension UIViewController {
    func route<T>(to destinationType: T.Type) where T : UIViewController {
        let identifier = String(describing: destinationType)
        guard let destinationViewController = self.storyboard?.instantiateViewController(identifier: identifier) as? T else { return }
        present(destinationViewController, animated: true)
    }
}