If I could change any one thing about Codable
, I'd generalize the compiler magic that makes it possible.
Focusing on Decodable
for a minute, if you could take a type, get a list of KeyPath
s, get the name of each, and construct an instance of the type by providing values for each key path, then:
-
Deodable
could probably be defined in the stdlib instead of the compiler. The rest of what it does—decoding values from formats—is already in the stdlib. -
The community could experiment with wrappers inside
init(from: Decoder)
that help with the pain points experienced here. It'd be possible to add a way to get what's currently the default synthesizedinit
and override the defaults of some properties. I think this experimentation could lead to better ideas for the stdlib. -
People could explore other solutions for problems that
Codable
isn't a great fit for. Maybe decoding JSON APIs would be better served by an API that was less focused on roundtripping values, e.g.
Encodable
could have a similar treatment.
One small change I think would help would be to add return type inference to the decode methods:
func decode<T>(
_ type: T.Type = T.self, // Add this default
forKey key: KeyedDecodingContainer<K>.Key
) throws -> T where T : Decodable
I understand the limitations and downsides of return type inference generally, but 99% of the time when I write a decodable implementation, I'm either assigning to a property or passing a value to an init. A default would remove a lot of tedium.