【问题标题】:Meta type of dictionary字典的元类型
【发布时间】:2018-01-06 12:38:25
【问题描述】:

我想编写一个接受任何类型的函数来确定它的工作。但我遇到了dictionary.type 的错误。它为其占位符的键请求特定类型。

有什么办法可以做到吗?

我可能会这样使用:

foo(type: type(of: someDict)) // someDict can be any type of dictionary.
// can be [String: Any] or [Int, Any] or [Double: Any] or [Character: Any], etc. 


func foo(type: Any.Type) {
    switch type {
    case is Int.Type:
        print("is Int")
    //case is Dictionary: // error, Reference to generic type 'Dictionary' requires arguments in <...>
    case is Dictionary<Hashable, Any>: // also error, Using 'Hashable' as a concrete type conforming to protocol 'Hashable' is not supported
        print("is Dictionary")
    default:
        print("don't know")
    }
}

【问题讨论】:

    标签: swift types protocols


    【解决方案1】:

    首先,您不应该使用Any 作为函数输入参数的类型。相反,您应该使您的函数通用。

    要解决匹配Dictionary 的元类型的问题,您只需将Hashable 更改为AnyHashable,这是Hashable 值的类型擦除容器类型。

    func foo<T>(type: T.Type) {
        switch type {
        case is Int.Type:
            print("is Int")
        case is Dictionary<AnyHashable, Any>.Type:
            print("is Dictionary")
        default:
            print("don't know")
        }
    }
    

    【讨论】:

    • 不能,因为我要这样写:func load(dict: [String: Any.Type]) -> [String:Any]
    • 所以,我会像这样传递:["IntKey": Int.self, "StringKey": String.self]
    • 虽然这会编译,但它似乎无法正确识别字典。如果我有一个 [String: Any] 或 [Int: Any] 并传递它 type(of: varName) 它不会将其识别为字典。只有 [AnyHashable: Any] 类型的 var 直接起作用。 (这是我尝试的方法)
    • 哦!那么,我不必写。似乎 AnyHashable 有效
    【解决方案2】:

    也许您应该使用Any 而不是Any.Type?这工作正常:

    let dict: [Int: Any] = [:]
    foo(type: dict) // is Dictionary
    foo(type: 12) // is Int
    foo(type: "12") // don't know
    
    func foo(type: Any) {
        switch type {
        case is Int:
            print("is Int")
        case is Dictionary<AnyHashable, Any>:
            print("is Dictionary")
        default:
            print("don't know")
        }
    }
    

    【讨论】:

    • 实际上,我正在编写一个函数来使用“UserDefaults.standard”加载数据。因此,我无法传递任何价值。我只能告诉类型和密钥来选择合适的方法来加载数据。
    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 2019-10-14
    相关资源
    最近更新 更多