Monday, January 7, 2019

Why Doesn’t JSONEncoder Conform to the Encoder Protocol?

Kaitlin Mahar:

Inspecting the source code for JSONEncoder, we see it’s a open type that internally uses a private type _JSONEncoder, which does conform to Encoder.


But why were they designed that way? Why not just make JSONEncoder an Encoder 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 the Encoder 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 (, 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.

Leave a Comment