Friday, July 14, 2017 [Tweets] [Favorites]

Swift.Codable

Mike Ash:

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 inside Person. 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 own CodingKeys with custom raw values.

Previously: Swift 4: JSON With Encoder and Encodable.

3 Comments

[…] Swift.Codable, Swift 4: JSON With Encoder and […]

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment