如何根据类型参数检查类型?

时间:2015-01-03 21:56:12

标签: swift

我正在尝试实现一个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
}

什么都行不通!我怎样才能做到这一点?谢谢!

1 个答案:

答案 0 :(得分:2)

在上一个示例中,更改

if vc is type 

if vc is T

T是您要查找的类型,而T.Type是元类型,提供有关类型T的信息。所有你真正使用T.Type的方法是在调用T时将getChildViewController修改为你想要的类型。