打开通用类型?

时间:2015-10-18 21:52:18

标签: swift generics

是否可以在Swift中打开泛型类型?

这是我的意思的一个例子:

func doSomething<T>(type: T.Type) {
    switch type {
    case String.Type:
        // Do something
        break;
    case Int.Type:
        // Do something
        break;
    default:
        // Do something
        break;
    }
}

尝试使用上面的代码时,我收到以下错误:

Binary operator '~=' cannot be applied to operands of type 'String.Type.Type' and 'T.Type'
Binary operator '~=' cannot be applied to operands of type 'Int.Type.Type' and 'T.Type'

有没有办法打开一个类型,或实现类似的东西? (根据泛型的类型调用具有泛型的方法并执行不同的操作)

1 个答案:

答案 0 :(得分:25)

您需要is模式:

func doSomething<T>(type: T.Type) {
    switch type {
    case is String.Type:
        print("It's a String")
    case is Int.Type:
        print("It's an Int")
    default:
        print("Wot?")
    }
}

请注意,通常不需要break语句,没有 Swift案件中的“默认漏洞”。