2016-12-07 74 views
3
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 

//我得到的错误不明确的参考成员“下标”如何扩展字典,允许使用下标与动态密钥?

我怎样才能让我的扩展让我给一个密钥,并用不带文字的下标,而是一个“动态”键字符串的形式?

+4

只需用'key:Key'替换'key:String'。 – user28434

+4

请注意,“Value:Any”是一个冗余约束。我也没有理由将'Key'限制为'ExpressibleByStringLiteral' - 如果'Key'不是'ExpressibleByStringLiteral',它会产生什么区别? – Hamish

回答

4

删除不必要的限制和直接使用KeyValue类型,无论你认为合适的。

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

只是key: Key替换key: String

extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any { 

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

     return self[key] as? Date 

    } 

} 
1

您可以通过“代理-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" 
相关问题