如何扩展允许使用带有动态键的下标的字典?

How to make an extension for dictionary that allows use of the subscript with a dynamic key?

extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {   

    func date(forKey key: String) -> Date? {

        return self[key] as? Date

    }

}

let dictionary: [String : Any] = ["mydate" : Date(), "otherkey" : "Rofl"]

dictionary.date(forKey:"mydate")  // should return a Date? object

// 我收到对成员的错误引用不明确 'subscript'

如何让我的扩展程序允许我提供一个键并使用下标而不是文字,而是字符串形式的 "dynamic" 键?

只需将 key: String 替换为 key: Key:

extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {

    func date(forKey key: Key) -> Date? {

        return self[key] as? Date

    }

}

删除不需要的约束并直接在您认为合适的地方使用 KeyValue 类型。

extension Dictionary {
    func date(forKey key: Key) -> Date? {
        return self[key] as? Date
    }
}

您可以通过 "proxy-ing" 日期查询来获取一些语法糖,如下所示:

struct DictionaryValueProxy<DictKey: Hashable, DictValue, Value> {
    private let dictionary: [DictKey:DictValue]

    init(_ dictionary: [DictKey:DictValue]) {
        self.dictionary = dictionary
    }

    subscript(key: DictKey) -> Value? {
        return dictionary[key] as? Value
    }
}

extension Dictionary {
    var dates: DictionaryValueProxy<Key, Value, Date> { return DictionaryValueProxy(self) }
}

然后您可以无缝地查询字典的日期:

let dict: [Int:Any] = [1: 2, 3: Date()]
dict.dates[1]                            // nil
dict.dates[3]                            // "Dec 7, 2016, 5:23 PM"