【问题标题】:How to check type against type parameter?如何根据类型参数检查类型?
【发布时间】:2015-01-03 21:56:11
【问题描述】:

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

没有任何作用!我怎样才能做到这一点?谢谢!

【问题讨论】:

    标签: swift


    【解决方案1】:

    在你的最后一个例子中,改变

    if vc is type 
    

    if vc is T
    

    T 是您要查找的类型,而 T.Type 是一个元类型,提供有关 T 类型的信息。您真正使用T.Type 的目的是将T 修复为您调用getChildViewController 时想要的类型。

    【讨论】:

    • 哦,好吧,这有点奇怪。我希望变量(“类型”)是类型。例如,在 Java 中可以这样做:void foo(Class&lt;?&gt; a) { String b = ""; if (a.isInstance(b)) {} }
    • 也许我无法正确判断,但这种语法有一些违反直觉的东西。无论如何,它有效,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2013-10-13
    相关资源
    最近更新 更多