No Generic Decoders?

Hi Jon,

This was a conscious choice in the API design, for three main reasons:

1. There is a big difference between the API surface exposed at the top-level for encoding and decoding and the middle levels. A method like `decode(_ type: T, from data: Data)` is really only appropriate at the top level of a given decoder, and likewise, exposing individual encoding and decoding containers is really only appropriate at the middle levels. We intentionally left these APIs separate to avoid exposing methods in inappropriate places (so the `Decoder` protocol doesn’t expose the top-level method)
2. Among top-level interfaces, there is variability in what different decoders can expose. `JSONDecoder`, for instance, exposes only a `decode(_ type: T, from data: Data)` method, while `PropertyListDecoder` has another method which also exposes the `PropertyListSerialization.PropertyListFormat` of the decoded data, which would not be appropriate to expose on `JSONDecoder`. In the future, these two might diverge further if we decide to specify the API even further, but more importantly, other decoders might find a different top-level API to be more appropriate than these methods (e.g. a format which only allows top-level dictionaries might want to expose only a decode method which accepts a dictionary type)
3. Given that, we found that it would be too confusing to expose top-level encoders and decoders as a separate type from `Encoder`/`Decoder` for not much benefit

If you find the concept useful for your own work and are willing to sacrifice some portability, you can always define a protocol with the interface appropriate for your project and have these decoders conform to that protocol.

— Itai

···

On 2 Sep 2017, at 18:47, Jon Shier via swift-users wrote:

Swift Users:
  I’ve been exploring the creation of Decodable response serializers for Alamofire. However, there doesn’t actually seem to be any way to express the notion of a generic decoder. The Decoder protocol itself doesn’t require a `decode(type:from:)` method, and neither JSONDecoder or PropertyListDecoder conform to Decoder in the first place. Were these facts conscious choices or oversights? It certainly seems very useful to be able to treat decoders generically.

Jon Shier
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users