Swift - 打开元类型

phn*_*mnn 3 swift

选项1:

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

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

    return "nothing"
}
Run Code Online (Sandbox Code Playgroud)

选项2:

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

    switch type {
    case [String].self:
        return "storageKey"
    default:
        return "nothing"
    }
}
Run Code Online (Sandbox Code Playgroud)

//

getKeyByType(type: [String].self)
Run Code Online (Sandbox Code Playgroud)

第一种方法工作正常,但第二种方法出现编译错误:

“[String].Type”类型的表达式模式无法与“T.Type”类型的值匹配

如何让 switch 与元类型一起工作?

phn*_*mnn 6

解决方案:

switch type {
case is [String].Type :
    return "storageKey"
default:
    return "nothing"
}
Run Code Online (Sandbox Code Playgroud)