是否可以在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'
有没有办法打开一个类型,或实现类似的东西? (根据泛型的类型调用具有泛型的方法并执行不同的操作)
答案 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案件中的“默认漏洞”。