【问题标题】:Swift - switch on metatypesSwift - 打开元类型
【发布时间】:2019-04-30 21:55:00
【问题描述】:

选项 1:

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

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

    return "nothing"
}

选项 2:

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

    switch type {
    case [String].self:
        return "storageKey"
    default:
        return "nothing"
    }
}

//

getKeyByType(type: [String].self)

第一种方法可以正常工作,但第二种我得到编译错误:

“[String].Type”类型的表达式模式不能匹配类型的值 'T.Type'

如何让开关与元类型一起使用?

【问题讨论】:

  • 如果你真的想让case [String].self 工作,你可以提供一个~= 的重载来比较两个Any.Type 值,例如func ~= (pattern: Any.Type, value: Any.Type) -&gt; Bool { return pattern == value }。那么如果SE-0090 发生过,你可以说case [String] :)

标签: swift


【解决方案1】:

解决方案:

switch type {
case is [String].Type :
    return "storageKey"
default:
    return "nothing"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-04
    • 2017-10-21
    • 2016-02-03
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 2015-03-20
    相关资源
    最近更新 更多