我正在尝试实现一个UIViewController扩展,它可以获得具有特定类型的第一个子视图控制器。
我试过了:
func getChildViewController(#type:UIViewController.Type) -> UIViewController? {
for vc:UIViewController in self.childViewControllers as [UIViewController] {
if vc is type { //<-- 'type is not a type'
return vc
}
}
return nil
}
和
func getChildViewController(#type:Type) -> UIViewController? { // "Type", doesn't exist
for vc:UIViewController in self.childViewControllers as [UIViewController] {
if vc is type {
return vc
}
}
return nil
}
这(部分来自How to pass a class type as a function parameter):
func getChildViewController<T>(#type:T.Type) -> UIViewController? {
for vc:UIViewController in self.childViewControllers as [UIViewController] {
if vc is type { //<-- 'type is not a type'
return vc
}
}
return nil
}
什么都行不通!我怎样才能做到这一点?谢谢!
答案 0 :(得分:2)
在上一个示例中,更改
if vc is type
到
if vc is T
T
是您要查找的类型,而T.Type
是元类型,提供有关类型T
的信息。所有你真正使用T.Type
的方法是在调用T
时将getChildViewController
修改为你想要的类型。