如何根据类型参数检查类型?
How to check type against type parameter?
我正在尝试实现一个 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
}
没有任何效果!我怎样才能做到这一点?谢谢!
在您的最后一个示例中,更改
if vc is type
到
if vc is T
T
是您要查找的类型,而 T.Type
是提供有关类型 T
信息的元类型。您真正使用 T.Type
的目的是将 T
固定为您调用 getChildViewController
.
时所需的类型
我正在尝试实现一个 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
}
没有任何效果!我怎样才能做到这一点?谢谢!
在您的最后一个示例中,更改
if vc is type
到
if vc is T
T
是您要查找的类型,而 T.Type
是提供有关类型 T
信息的元类型。您真正使用 T.Type
的目的是将 T
固定为您调用 getChildViewController
.