Advertisement
Guest User

Untitled

a guest
Sep 17th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.95 KB | None | 0 0
  1. struct ConversationIncluded: Decodable {
  2.    
  3.     let type: String
  4.     let attributes: Any?
  5.    
  6.     private typealias AttributesDecoder = (KeyedDecodingContainer<CodingKeys>) throws -> Any
  7.     private typealias AttributesEncoder = (Any, inout KeyedEncodingContainer<CodingKeys>) throws -> Void
  8.    
  9.     private static var decoders: [String: AttributesDecoder] = [:]
  10.     private static var encoders: [String: AttributesEncoder] = [:]
  11.    
  12.     private enum CodingKeys: String, CodingKey {
  13.         case type
  14.         case attributes
  15.     }
  16.    
  17.     init(from decoder: Decoder) throws {
  18.         let container = try decoder.container(keyedBy: CodingKeys.self)
  19.         type = try container.decode(String.self, forKey: .type)
  20.         print("@@@@ \(String(describing: type))")
  21.        
  22.         if let decode = ConversationIncluded.decoders[type] {
  23.             attributes = try decode(container)
  24.         } else {
  25.             attributes = nil
  26.         }
  27.     }
  28.    
  29.     func encode(to encoder: Encoder) throws {
  30.         var container = encoder.container(keyedBy: CodingKeys.self)
  31.        
  32.         try container.encode(type, forKey: .type)
  33.        
  34.         if let attributes = self.attributes {
  35.             guard let encode = ConversationIncluded.encoders[type] else {
  36.                 let context = EncodingError.Context(codingPath: [], debugDescription: "Invalid attachment: \(type).")
  37.                 throw EncodingError.invalidValue(self, context)
  38.             }
  39.             try encode(attributes, &container)
  40.         } else {
  41.             try container.encodeNil(forKey: .attributes)
  42.         }
  43.     }
  44.    
  45.     static func register<A: Codable>(_ type: A.Type, for typeName: String) {
  46.         decoders[typeName] = { container in
  47.             try container.decode(A.self, forKey: .attributes)
  48.         }
  49.  
  50.         encoders[typeName] = { payload, container in
  51.             try container.encode(payload as! A, forKey: .attributes)
  52.         }
  53.     }
  54.    
  55.    
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement