Swift.Codable
Reflection is not a particularly good solution to this problem. It’s easy to get it wrong and create security bugs. It’s less able to use static typing, so more errors happen at runtime rather than compile time. And it tends to be pretty slow, since the code has to be completely general and does lots of string lookups with type metadata.
Swift has taken the approach of compile-time code generation rather than runtime reflection. This means that some of the knowledge has to be built in to the compiler, but the result is fast and takes advantage of static typing, while still remaining easy to use.
[…]
The compiler generates a
CodingKeys
type nested insidePerson
. If we did it ourselves, that nested type would look like this[…] If we need different names, we can easily accomplish this by providing our ownCodingKeys
with custom raw values.
Previously: Swift 4: JSON With Encoder and Encodable.