是否可以在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;
}
}
Run Code Online (Sandbox Code Playgroud)
尝试使用上面的代码时,我收到以下错误:
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'
Run Code Online (Sandbox Code Playgroud)
有没有办法打开一个类型,或实现类似的东西?(根据泛型的类型调用具有泛型的方法并执行不同的操作)
Mar*_*n R 31
你需要这个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?")
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,break通常不需要语句,Swift案例中没有"默认的突破".
| 归档时间: |
|
| 查看次数: |
4869 次 |
| 最近记录: |