我正在尝试扩展具有嵌套约束的类型,但是我对于如何实现如下所示有点迷茫:
extension KeyedDecodingContainer where K : CodingKey,
K : RawRepresentable,
RawValue : AnyHashable {
/// A helper method
func decode<T>(into object: inout [K.RawValue : Any], _ type: T.Type,
forKey: key: KeyedDecodingContainer<K>.Key) throws where T : Decodable {
object[key.rawValue] = try self.decode(type, forKey: key) as Any
}
}
示例用法为:
struct Value: Decodable {
enum CodingKeys: String, CodingKey {
case id
}
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
var object = [String : Any]()
try c.decode(into: &object, Int.self, forKey: .id)
}
}
有可能吗?预先感谢!
答案 0 :(得分:1)
是的,你快到了!
KeyedDecodingContainer
没有RawValue
类型,是K
,因为K
符合RawRepresentable
AnyHashable
是Hashable
的具体实现。要限制通用参数时,请使用Hashable
。KeyedDecodingContainer<K>.Key
可以简化为Key
,因为您属于KeyedDecodingContainer<K>
的范围。as Any
。一切都可以隐式转换为Any
。extension KeyedDecodingContainer where K : CodingKey,
K : RawRepresentable,
K.RawValue : Hashable {
/// A helper method
func decode<T>(into object: inout [K.RawValue : Any], _ type: T.Type,
forKey key: Key) throws where T : Decodable {
object[key.rawValue] = try self.decode(type, forKey: key)
}
}