Why Doesn’t JSONEncoder Conform to the Encoder Protocol?
Inspecting the source code for
JSONEncoder
, we see it’s aopen
type that internally uses aprivate
type_JSONEncoder
, which does conform toEncoder
.[…]
But why were they designed that way? Why not just make
JSONEncoder
anEncoder
too?In short, the answer is that they provide very different APIs. The
JSONEncoder
API is designed to provide a single, simple entry point into encoding, and theEncoder
protocol provides a completely different API for customizing how types are encoded.
This makes sense, though it’s kind of odd that the facade and the protocol for the private types both use the same word (Encoder
/Decoder
). Cocoa distinguishes between NSArchiver
/NSUnarchiver
, which you use directly, and NSCoder
, which is passed to you. Although, that’s also a bit messy because the archivers are subclasses of NSCoder
, and so all the other methods are still there.
1 Comment RSS · Twitter
When implementing a SQLite encoder/decoder (https://shareup.app/blog/encoding-and-decoding-sqlite-in-swift/), I too was initially confused by the labyrinth of similarly-named types, but it turned out to be a pretty elegant and flexible design, albeit one that requires a fair amount of boilerplate code.