Parsing in Swift: a DTO-based Approach

<p>Turning JSON into actual Swift types is something most apps have to deal with eventually. At the beginning of Swift, Apple was not opinionated about how we should approach that task. So people came up with a bunch of&nbsp;<a href="https://github.com/JohnSundell/Unbox" rel="noopener ugc nofollow" target="_blank">different</a>&nbsp;<a href="https://github.com/tristanhimmelman/ObjectMapper" rel="noopener ugc nofollow" target="_blank">libraries</a>&nbsp;to do so. Some of them are&nbsp;<a href="https://github.com/thoughtbot/Argo" rel="noopener ugc nofollow" target="_blank">quite esoteric</a>. Fortunately, Apple came up with its own first-party solution,&nbsp;<a href="https://developer.apple.com/documentation/swift/codable#" rel="noopener ugc nofollow" target="_blank">Codable</a>.</p> <p>Turning JSON into Swift types can be as easy as conforming those types to the&nbsp;<code>Codable</code>&nbsp;protocol. You might not need to do anything else. The compiler will do its magic and synthesize the appropriate parsing code for you. That&rsquo;s lovely. There&rsquo;s no better code than the one you don&rsquo;t have to write. Sometimes, the &ldquo;parsing code&rdquo; you have to write is minimal, providing a&nbsp;<code>CodingKeys</code>&nbsp;enum with the appropriate mapping between your type property names and the JSON keys.</p> <p><a href="https://betterprogramming.pub/parsing-in-swift-a-dto-based-approach-5edca55eb57a"><strong>Website</strong></a></p>
Tags: Parsing Swift