开启通用类型? [英] Switching on a generic type?

查看:71
本文介绍了开启通用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to switch on a generic type in 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;
    }
}

尝试使用上面的代码时,出现以下错误:

When trying to use the code above, I get the following errors:

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'

是否可以打开类型或实现类似功能? (调用具有泛型的方法,并根据泛型的类型执行不同的操作)

Is there a way to switch on a type, or to achieve something similar? (calling a method with a generic and performing different actions depending on the type of the generic)

推荐答案

您需要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情况下为默认失败".

Note that the break statements are usually not needed, there is no "default fallthrough" in Swift cases.

这篇关于开启通用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆