Swift-switch-on元类型

Swift-switch-on元类型,swift,Swift,备选案文1: func getKeyByType<T:Decodable>(type: T.Type) -> String { if (type == [String].self){ return "storageKey" } return "nothing" } 第一个方法工作正常,但第二个方法出现编译错误: 类型为“[String]”的表达式模式。类型“”不能与类型“”的值匹配 ‘T型’ 如何让交换机与元类型一起工作?解决方案:

备选案文1:

func getKeyByType<T:Decodable>(type: T.Type) -> String {

    if (type == [String].self){
        return "storageKey"
    }

    return "nothing"
}
第一个方法工作正常,但第二个方法出现编译错误:

类型为“[String]”的表达式模式。类型“”不能与类型“”的值匹配 ‘T型’

如何让交换机与元类型一起工作?

解决方案:

switch type {
case is [String].Type :
    return "storageKey"
default:
    return "nothing"
}
比较如果你真的想让case[String].self工作,你可以提供一个重载~=来比较两个Any.Type值,例如func~=pattern:Any.Type,value:Any.Type->Bool{return pattern==value}。如果发生,你可以说case[String]:
getKeyByType(type: [String].self)
switch type {
case is [String].Type :
    return "storageKey"
default:
    return "nothing"
}