具有多种类型约束的复杂扩展
Complex extensions with multiple type constraints
我正在尝试扩展具有嵌套约束的类型,但我有点不知如何实现如下内容:
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)
}
}
有可能吗?提前致谢!
是的,你快到了!
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)
}
}
我正在尝试扩展具有嵌套约束的类型,但我有点不知如何实现如下内容:
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)
}
}
有可能吗?提前致谢!
是的,你快到了!
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)
}
}