简体   繁体   English

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

[英]How to pass type as func argument?

When trying to describe routing procedure in order to make VC more lean I faced a problem.当试图描述路由过程以使 VC 更精简时,我遇到了一个问题。 When passing type as func argument I get a compile error将类型作为 func 参数传递时,出现编译错误

Cannot find type 'destinationType' in scope在 scope 中找不到类型“destinationType”

in the following code.在下面的代码中。 Please have a look and explain what am I doing wrong way.请看一下并解释我做错了什么。

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

Nothing in your code relies upon the type of the view controller that comes from the storyboard.您的代码中没有任何内容依赖于来自 storyboard 的视图 controller 的类型。 So you don't need a type, a generic, or any of the other accoutrements.因此,您不需要类型、泛型或任何其他装备。 All you need is the identifier, and you can say "fetch that view controller and present it":您所需要的只是标识符,您可以说“获取该视图 controller 并呈现它”:

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

However, if you insist on the generic and the cast, the type you are looking for is not destinationType (which is a metatype, not a type at all) — it's T :但是,如果您坚持泛型和强制转换,那么您正在寻找的类型不是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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM