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
//我得到了成员’下标’的错误模糊引用
如何使我的扩展允许我给出一个键并使用下标而不是文字,而是使用字符串形式的“动态”键?
解决方法
删除不需要的约束,并在您认为合适的地方直接使用键或值类型.
extension Dictionary { func date(forKey key: Key) -> Date? { return self[key] as? Date } }