Flight-School / AnyCodable

Type-erased wrappers for Encodable, Decodable, and Codable values
https://flight.school/books/codable
MIT License
1.28k stars 132 forks source link

Is there a way to create adhoc types conforming to protocols #81

Open avnerbarr opened 6 months ago

avnerbarr commented 6 months ago

I have a use case where there can be multiple datasources accessed through a strategy pattern. Those strategies return similar objects (json from the network).

Internally they handle the data differently and can't share the same data model, but for the functionality using those API's this doesn't really matter.

I'd like to "proxy" the data behind some protocol which is backed by the JSON data itself. Is there a good pattern for that?

I'll share an example:

protocol EventType {
   associatedtype PointType: DataPointType
   var timestamp: Int {get}
   var value: Double {get}
   var data : PointType
}

protocol DataPointType {
   var field1: Int {get}
   var field2: String {get}
    // etc. etc.
}

   .... get some data as json ....
   let jsonData: AnyCodable = .... get the data from somewhere .... there are many internal types and don't want to craft custom types for each one
  // jsonData structure adheres to EventType .... 
   /// I need a concrete dynamic object conforming to the EventType  

// some sort of generic object which implements the EventType protocol
let typedData = Proxy<EventType>(jsonData) // behave like the protocol with the backing jsonData and I don't want to create. a concrete type implementing EventType