Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct ConversationIncluded: Decodable {
- let type: String
- let attributes: Any?
- private typealias AttributesDecoder = (KeyedDecodingContainer<CodingKeys>) throws -> Any
- private typealias AttributesEncoder = (Any, inout KeyedEncodingContainer<CodingKeys>) throws -> Void
- private static var decoders: [String: AttributesDecoder] = [:]
- private static var encoders: [String: AttributesEncoder] = [:]
- private enum CodingKeys: String, CodingKey {
- case type
- case attributes
- }
- init(from decoder: Decoder) throws {
- let container = try decoder.container(keyedBy: CodingKeys.self)
- type = try container.decode(String.self, forKey: .type)
- print("@@@@ \(String(describing: type))")
- if let decode = ConversationIncluded.decoders[type] {
- attributes = try decode(container)
- } else {
- attributes = nil
- }
- }
- func encode(to encoder: Encoder) throws {
- var container = encoder.container(keyedBy: CodingKeys.self)
- try container.encode(type, forKey: .type)
- if let attributes = self.attributes {
- guard let encode = ConversationIncluded.encoders[type] else {
- let context = EncodingError.Context(codingPath: [], debugDescription: "Invalid attachment: \(type).")
- throw EncodingError.invalidValue(self, context)
- }
- try encode(attributes, &container)
- } else {
- try container.encodeNil(forKey: .attributes)
- }
- }
- static func register<A: Codable>(_ type: A.Type, for typeName: String) {
- decoders[typeName] = { container in
- try container.decode(A.self, forKey: .attributes)
- }
- encoders[typeName] = { payload, container in
- try container.encode(payload as! A, forKey: .attributes)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement