<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Leandro Fournier on Medium]]></title>
        <description><![CDATA[Stories by Leandro Fournier on Medium]]></description>
        <link>https://medium.com/@lean4nier?source=rss-114f0eb90da9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_6iRGZl7IKETgATGo9mPeg.jpeg</url>
            <title>Stories by Leandro Fournier on Medium</title>
            <link>https://medium.com/@lean4nier?source=rss-114f0eb90da9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:04:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lean4nier/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Custom encoding and decoding JSON in Swift]]></title>
            <link>https://levelup.gitconnected.com/custom-encoding-and-decoding-json-in-swift-a99c80b280e7?source=rss-114f0eb90da9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a99c80b280e7</guid>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[decode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[encode]]></category>
            <dc:creator><![CDATA[Leandro Fournier]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 16:28:12 GMT</pubDate>
            <atom:updated>2020-04-24T00:52:07.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/651/0*-t2P3atrbgHMKR6P.jpg" /></figure><blockquote>This post was originally written by me at <a href="https://www.leandrofournier.com/custom-encoding-and-decoding-json/">Swift Delivery</a>.</blockquote><p>In our last <a href="https://levelup.gitconnected.com/working-with-json-in-swift-c5faea0b19a1">Working with JSON in Swift series</a>, we explore various items:</p><ul><li>Codable protocol, which contains two other protocols: Encodable and Decodable</li><li>How to decode a JSON data object into a readable Swift struct</li><li>Usage of custom keys</li><li>Custom objects creation</li><li>Arrays</li><li>Different top level entities</li></ul><p>That’s enough for a basic usage of JSON in Swift, which will enable us to read JSON data (decode) and create a new object which can be converted back to JSON (encode) and send it, for instance, to a RESTFul API.</p><p>So, first things first: let’s create an object and convert it to a JSON data format.</p><h3>Encoding</h3><h4>Default encoding</h4><p>Let’s assume we have the following struct for insects:</p><pre>struct Insect: Codable {<br>    let insectId: Int<br>    let name: String<br>    let isHelpful: Bool<br>    <br>    enum CodingKeys: String, CodingKey {<br>        case insectId = &quot;insect_id&quot;<br>        case name<br>        case isHelpful = &quot;is_helpful&quot;<br>    }<br>}</pre><p>To sum up, we have three properties. <strong>insectId </strong>for the insect identifier, <strong>name</strong> for its name and <strong>isHelpful</strong> to specify if the insect is helpful or not to our garden. Two of these properties use custom keys (<strong>insectId</strong> and <strong>isHelpful</strong>).</p><p>Now let’s create an insect:</p><pre>let newInsect = Insect(insectId: 1006, name: &quot;ants&quot;, isHelpful: true)</pre><p>Our RESTful API expects to receive a JSON with this new insect information. Then we have to encode it:</p><pre>let encoder = JSONEncoder() <br>let insectData: Data? = try? encoder.encode(newInsect)</pre><p>That was easy: now <strong>insectData</strong> is an object of type Data?. We might want to check whether the encoding actually worked (just a check, you probably won&#39;t do this in your code). Let&#39;s rewrite the code above and use some optional unwrapping:</p><pre>let encoder = JSONEncoder()<br>if let insectData = try? encoder.encode(newInsect),<br>    let jsonString = String(data: insectData, encoding: .utf8)<br>    {<br>    print(jsonString)<br>}</pre><ol><li>Create the encoder</li><li>Try to encode the object we’ve created</li><li>Convert, if possible, the Data object into a String</li></ol><p>Then we print out the result which will look like this:</p><pre>{&quot;name&quot;:&quot;ants&quot;,&quot;is_helpful&quot;:true,&quot;insect_id&quot;:1006}</pre><blockquote>Note that the keys used while encoding are not the custom keys (<strong>insectId</strong> and <strong>isHelpful</strong>) but the expected keys (<strong>insect_id</strong> and <strong>is_helpful</strong>). Nice!</blockquote><h4>Custom encoding</h4><p>Let’s suppose our RESTful API expects to receive the name of the insect uppercased. We need to create our own implementation of the encoding method so to make sure the name of the insect is sent uppercased. We must implement the method <strong>func</strong> encode(to encoder: Encoder) <strong>throws</strong> of the Encodable protocol inside our <strong>Insect</strong> struct.</p><pre>struct Insect: Codable {<br>    let insectId: Int<br>    let name: String<br>    let isHelpful: Bool<br>    <br>    enum CodingKeys: String, CodingKey {<br>        case insectId = &quot;insect_id&quot;<br>        case name<br>        case isHelpful = &quot;is_helpful&quot;<br>    }<br>    <br>    func encode(to encoder: Encoder) throws {<br>        var container = encoder.container(keyedBy: CodingKeys.self)<br>        try container.encode(insectId, forKey: .insectId)<br>        try container.encode(name.uppercased(), forKey: .name)<br>        try container.encode(isHelpful, forKey: .isHelpful)<br>    }<br>}</pre><p>Line 13 is where we create a container where encoded values will be stored. The container MUST be a var because it&#39;s mutable and MUST receive the keys to be used.</p><p>Lines 14 to 16 are used to encode the values into the container, which is done using try because any of these can throw an error.</p><p>Now, look at line 15: we don’t just put the value as it is but we uppercase it, which is main reason we’re implementing a custom encoding.</p><p>If you run the code above, where we create the <strong>Insect</strong> “ants”, we’ll see that after encoding and converting the resulting JSON Data into a String we get the following:</p><pre>{&quot;name&quot;:&quot;ANTS&quot;,&quot;is_helpful&quot;:true,&quot;insect_id&quot;:1006}</pre><p>As you might have seen, the name of the insect is now uppercased despite we’ve created it lowercased. How cool is that!</p><h3>Custom decoding</h3><p>So far we’ve been relying on the default decoding method of the Decodable protocol. But let&#39;s take a look at another scenario.</p><pre>[<br>   {<br>      &quot;insect_id&quot;:1001,<br>      &quot;name&quot;:&quot;BEES&quot;,<br>      &quot;details&quot;:{<br>         &quot;is_helpful&quot;:true<br>      }<br>   },<br>   {<br>      &quot;insect_id&quot;:1002,<br>      &quot;name&quot;:&quot;LADYBUGS&quot;,<br>      &quot;details&quot;:{<br>         &quot;is_helpful&quot;:true<br>      }<br>   },<br>   {<br>      &quot;insect_id&quot;:1003,<br>      &quot;name&quot;:&quot;SPIDERS&quot;,<br>      &quot;details&quot;:{<br>         &quot;is_helpful&quot;:true<br>      }<br>   },<br>   {<br>      &quot;insect_id&quot;:2001,<br>      &quot;name&quot;:&quot;TOMATO HORN WORMS&quot;,<br>      &quot;details&quot;:{<br>         &quot;is_helpful&quot;:false<br>      }<br>   },<br>   {<br>      &quot;insect_id&quot;:2002,<br>      &quot;name&quot;:&quot;CABBAGE WORMS&quot;,<br>      &quot;details&quot;:{<br>         &quot;is_helpful&quot;:false<br>      }<br>   },<br>   {<br>      &quot;insect_id&quot;:2003,<br>      &quot;name&quot;:&quot;CABBAGE MOTHS&quot;,<br>      &quot;details&quot;:{<br>         &quot;is_helpful&quot;:false<br>      }<br>   }<br>]</pre><p>The API is retrieving the <strong>is_helpful</strong> property inside a <strong>details</strong> entity. But we don’t want to create a <strong>Details</strong> object: we just want to flatten that object so we can use our existing <strong>Insect </strong>object.</p><p>Time to use our own implementation of the <strong>init</strong>(from decoder: Decoder) <strong>throws</strong> method of the Decodable protocol and some extra work. Let&#39;s get started.</p><p>First of all, coding keys has changed because <strong>is_helpful</strong> is not a key in the same level as before AND there’s a new one called <strong>details</strong>. To fix that:</p><pre>enum CodingKeys: String, CodingKey {<br>        case insectId = &quot;insect_id&quot;<br>        case name<br>        case details<br>    }<br>    <br>    enum DetailsCodingKeys: String, CodingKey {<br>        case isHelpful = &quot;is_helpful&quot;<br>    }</pre><p>In line 4 we replace the existing key with the new one, <strong>details</strong>.</p><p>In lines 7 and 9 we create a new set of keys, the ones that exist inside <strong>details</strong>, which in this case is just one, <strong>isHelpful</strong>.</p><blockquote>Note that we didn’t touch the properties of the <strong>Insect</strong> struct.</blockquote><p>Now let’s dive into the decoder initialization:</p><pre>init(from decoder: Decoder) throws {<br>   let container = try decoder.container(keyedBy: CodingKeys.self)<br>        <br>   insectId = try container.decode(Int.self, forKey: .insectId)<br>   name = try container.decode(String.self, forKey: .name)<br>   let details = try container.nestedContainer(keyedBy: DetailsCodingKeys.self, forKey: .details)<br>   isHelpful = try details.decode(Bool.self, forKey: .isHelpful)<br>}</pre><p>In line 2 we create the container which decodes the whole JSON structure.</p><p>In line 4 and 5 we just decode the Int value for the <strong>insectId</strong> property and the String value for the <strong>name</strong> property.</p><p>In line 6 we grab the nested container under the <strong>details</strong> key which is keyed by the brand new <strong>DetailsCodingKeys</strong> enum.</p><p>In line 7 we just decode the Bool value for the <strong>isHelpful</strong> property inside our new <strong>details</strong> container.</p><p>BUT that’s not it. Since our <strong>CodingKeys</strong> has changed by adding the <strong>details</strong> case, our custom encoding implementation must be fixed. So let’s do that:</p><pre>func encode(to encoder: Encoder) throws {<br>    var container = encoder.container(keyedBy: CodingKeys.self)<br>    try container.encode(insectId, forKey: .insectId)<br>    try container.encode(name.uppercased(), forKey: .name)<br>    var details = container.nestedContainer(keyedBy: DetailsCodingKeys.self, forKey: .details)<br>    try details.encode(isHelpful, forKey: .isHelpful)<br>}</pre><p>We just changed the way we encode the <strong>isHelpful</strong> property.</p><p>In line 5 we create a new nested container, using the keys inside the <strong>DetailsCodingKeys</strong> enum and to be used inside the <strong>details </strong>entity inside our JSON.</p><p>In line 6 we encode <strong>isHelpful</strong> INSIDE the brand new <strong>details </strong>nested container.</p><p>So, to sum up, our <strong>Insect</strong> struct looks like this:</p><pre>struct Insect: Codable {<br>    let insectId: Int<br>    let name: String<br>    let isHelpful: Bool<br>    <br>    enum CodingKeys: String, CodingKey {<br>        case insectId = &quot;insect_id&quot;<br>        case name<br>        case details<br>    }<br>    <br>    enum DetailsCodingKeys: String, CodingKey {<br>        case isHelpful = &quot;is_helpful&quot;<br>    }<br>    <br>    init(from decoder: Decoder) throws {<br>        let container = try decoder.container(keyedBy: CodingKeys.self)<br>        <br>        insectId = try container.decode(Int.self, forKey: .insectId)<br>        name = try container.decode(String.self, forKey: .name)<br>        let details = try container.nestedContainer(keyedBy: DetailsCodingKeys.self, forKey: .details)<br>        isHelpful = try details.decode(Bool.self, forKey: .isHelpful)<br>        <br>    }<br>    <br>    func encode(to encoder: Encoder) throws {<br>        var container = encoder.container(keyedBy: CodingKeys.self)<br>        try container.encode(insectId, forKey: .insectId)<br>        try container.encode(name.uppercased(), forKey: .name)<br>        var details = container.nestedContainer(keyedBy: DetailsCodingKeys.self, forKey: .details)<br>        try details.encode(isHelpful, forKey: .isHelpful)<br>    }<br>}</pre><p>If we decode it:</p><pre>let decoder = JSONDecoder()<br>if let insects = try? decoder.decode([Insect].self, from: jsonData!) {<br>    print(insects)<br>}</pre><p>We’ll get something like this:</p><pre>[__lldb_expr_54.Insect(insectId: 1001, name: &quot;BEES&quot;, isHelpful: true), __lldb_expr_54.Insect(insectId: 1002, name: &quot;LADYBUGS&quot;, isHelpful: true), __lldb_expr_54.Insect(insectId: 1003, name: &quot;SPIDERS&quot;, isHelpful: true), __lldb_expr_54.Insect(insectId: 2001, name: &quot;TOMATO HORN WORMS&quot;, isHelpful: false), __lldb_expr_54.Insect(insectId: 2002, name: &quot;CABBAGE WORMS&quot;, isHelpful: false), __lldb_expr_54.Insect(insectId: 2003, name: &quot;CABBAGE MOTHS&quot;, isHelpful: false)]</pre><p>As you can see, there’s no <strong>details</strong> entity: just our struct properties.</p><p>The encoding will work as expected as well.</p><p>This post, plus the previous series, sums up pretty much the most common scenarios you may run into when working with JSON in Swift.</p><h3>Need more information?</h3><p>Ben Scheirman’s <a href="https://benscheirman.com/2017/06/swift-json/">Ultimate Guide to JSON Parsing with Swift</a> is the most useful source I could find for this subject.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a99c80b280e7" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/custom-encoding-and-decoding-json-in-swift-a99c80b280e7">Custom encoding and decoding JSON in Swift</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with JSON in Swift]]></title>
            <link>https://levelup.gitconnected.com/working-with-json-in-swift-c5faea0b19a1?source=rss-114f0eb90da9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5faea0b19a1</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[decodable]]></category>
            <dc:creator><![CDATA[Leandro Fournier]]></dc:creator>
            <pubDate>Fri, 13 Mar 2020 15:58:32 GMT</pubDate>
            <atom:updated>2020-04-23T17:01:15.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*26ma6oTi3og7c_8V9ehD_A.png" /></figure><p>DISCLAIMER: In this series of posts you’ll learn to work with JSON, not with JASON, the evil character from <em>Friday the 13th </em>series. Besides, working with JSON has become a pleasure since Swift 4… while JASON keeps being mean. So, drop your hockey mask and start coding!</p><blockquote>This post was originally written by me at <a href="https://www.leandrofournier.com/">Swift Delivery</a>: <a href="https://www.leandrofournier.com/working-with-json-part-1/">Part 1</a>: introducing Codable, JSONDecoder and a simple example. <a href="https://www.leandrofournier.com/working-with-json-part-2/">Part 2</a>: using custom keys and custom objects. <a href="https://www.leandrofournier.com/working-with-json-part-3/">Part 3</a>: working with Arrays and top level entities cases.</blockquote><h3>Basics</h3><p>Let’s assume you have the following JSON:</p><pre>{<br>	&quot;productId&quot;: 1423,<br>	&quot;name&quot;: &quot;Hockey Mask&quot;,<br>	&quot;color&quot;: &quot;white&quot;,<br>	&quot;price&quot;: 39.90<br>}</pre><p>You probably received this JSON response from an API request or you read a file content, which is a .json file. Either way, the common scenario is that you ended up having a Data type.</p><p>First, let’s create a Struct which contains our data structure:</p><pre>struct Product: Codable {<br>    let productId: Int<br>    let name: String<br>    let color: String?<br>    let price: Float<br>}</pre><p>The keyword here is Codable, which is a protocol. Actually, it’s a <em>protocol composition type</em> since it contains two protocols: Encodable and Decodable. Basically, Encodable lets you convert a type back to an external representation (i.e. Data), while Decodable does the opposite thing.</p><p>In this example, we want to convert from Data to Product, we could have used just Decodable. But later on we might want to do the other way around (i.e. send something back to an API, store the data in UserDefaults, etc). So let’s keep it as Codable.</p><p>Now, let’s convert our Data to Product:</p><pre>let decoder = JSONDecoder()<br>if let product = try? decoder.decode(Product.self, from: jsonData) {<br>    print(product)<br>}</pre><ol><li>We instantiate JSONDecoder, which “<a href="https://developer.apple.com/documentation/foundation/jsondecoder">decodes instances of a data type from JSON objects</a>“.</li><li>We use option binding (instead of force unwrapping) to unwrap the result or fail gracefully. You may opt to use try and catch the errors the decoder might throw.</li><li>Output the result.</li></ol><p>Here’s what we get:</p><pre>Product(productId: 1423, name: &quot;Hockey Mask&quot;, color: Optional(&quot;white&quot;), price: 39.9)</pre><h3>Custom keys</h3><p>APIs often use snake case convention for naming keys (this_is_snake_case)… or even kebab case (this-is-kebab-case). Snake case is not a very Swifty thing because it doesn’t match the naming guidelines. Swift loves camel case (thisIsCamelCase). So if you get something like this:</p><pre>{<br>    &quot;product_id&quot;: 1423,<br>    &quot;name&quot;: &quot;Hockey Mask&quot;,<br>    &quot;color-name&quot;: &quot;white&quot;,<br>    &quot;price-key-to-piss-the-developer-off&quot;: 39.90<br>}</pre><p>It’s not a good practice to mirror those names so you should better create custom keys. Like this:</p><pre>struct Product: Codable {<br>    let productId: Int<br>    let name: String<br>    let colorName: String?<br>    let price: Float<br>    <br>    enum CodingKeys: String, CodingKey {<br>          case productId = &quot;product_id&quot;<br>          case name<br>          case colorName = &quot;color-name&quot;<br>          case price = &quot;price-key-to-piss-the-developer-off&quot;<br>    }<br>}</pre><ul><li><strong>Lines 2 to 5.</strong> We set our object property names as they best fit our needs.</li><li><strong>Line 7. </strong>The keyword here is CodingKeys, which is a Coding Key enumeration. It connects each property to a value in the encoded format.</li><li><strong>Lines 8 to 11. </strong>For each property we define which key to use in the encoded format.</li></ul><p>Here’s the output:</p><pre>Product(productId: 1423, name: &quot;Hockey Mask&quot;, colorName: Optional(&quot;white&quot;), price: 39.9)</pre><h3>Custom objects</h3><p>Let’s say we have this JSON:</p><pre>{<br>    &quot;productId&quot;: 1423,<br>    &quot;name&quot;: &quot;Hockey Mask&quot;,<br>    &quot;color&quot;: &quot;white&quot;,<br>    &quot;price&quot;: {<br>        &quot;price&quot;: 39.90,<br>        &quot;currency&quot;: &quot;USD&quot;,<br>        &quot;formatted&quot;: &quot;39.90 USD&quot;<br>    }<br>}</pre><p>It’s a very common scenario and, fortunately, the Codable protocol makes our lives very easy: we just need to create an object Price which conforms to the Codable protocol as well and then use it as the type for our “price” property:</p><pre>struct Price: Codable {<br>    let price: Float<br>    let currency: String<br>    let formatted: String<br>}   <br><br>struct Product: Codable {<br>    let productId: Int<br>    let name: String<br>    let color: String?<br>    let price: Price?<br>}</pre><p>Here’s the output:</p><pre>Product(productId: 1423, name: &quot;Hockey Mask&quot;, color: Optional(&quot;white&quot;), price: Optional(__lldb_expr_3.Price(price: 39.9, currency: &quot;USD&quot;, formatted: &quot;39.90 USD&quot;)))</pre><p>You can use custom keys in custom objects as well, as explained above.</p><h3>Arrays</h3><p>Working with arrays inside JSON is easy peasy. Let’s take this example:</p><pre>{<br>   &quot;productId&quot;:1423,<br>   &quot;name&quot;:&quot;Hockey Mask&quot;,<br>   &quot;availableColors&quot;:[<br>      &quot;white&quot;,<br>      &quot;brown&quot;,<br>      &quot;black&quot;<br>   ],<br>   &quot;price&quot;:39.90<br>}</pre><p>The Product object will look like this:</p><pre>struct Product: Codable {<br>    let productId: Int<br>    let name: String<br>    let availableColors: [String]<br>    let price: Float<br>}</pre><p>As you can see in line 4, we set the property availableColors to an array of String objects.</p><p>Let’s take a more complex example:</p><pre>{<br>   &quot;productId&quot;:1423,<br>   &quot;name&quot;:&quot;Hockey Mask&quot;,<br>   &quot;availableColors&quot;:[<br>      &quot;white&quot;,<br>      &quot;brown&quot;,<br>      &quot;black&quot;<br>   ],<br>   &quot;price&quot;:39.90,<br>   &quot;stores&quot;:[<br>      {<br>         &quot;name&quot;:&quot;Gerry Cosby &amp; Co., Inc.&quot;,<br>         &quot;address&quot;:&quot;11 Pennsylvania Plaza, New York, NY 10001, United States&quot;,<br>         &quot;phone&quot;:&quot;+1 877-563-6464&quot;<br>      },<br>      {<br>         &quot;name&quot;:&quot;National Hockey League&quot;,<br>         &quot;address&quot;:&quot;1185 6th Ave, New York, NY 10036, United States&quot;,<br>         &quot;phone&quot;:&quot;+1 212-789-2000&quot;<br>      },<br>      {<br>         &quot;name&quot;:&quot;Modell&#39;s Sporting Goods&quot;,<br>         &quot;address&quot;:&quot;234 W 42nd St, New York, NY 10036, United States&quot;,<br>         &quot;phone&quot;:&quot;+1 212-764-7030&quot;<br>      }<br>   ]<br>}</pre><p>There’s a new field: “stores”. First, we create a struct for that:</p><pre>struct Store: Codable {<br>    let name: String<br>    let address: String<br>    let phone: String?<br>}</pre><p>Note that we set phone as an optional because we’re assuming the API documentation says that this field may not be in the response for all the entries.</p><p>Now let’s use it:</p><pre>struct Product: Codable {<br>    let productId: Int<br>    let name: String<br>    let availableColors: [String]<br>    let price: Float<br>    let stores: [Store]<br>}</pre><p>As simple as that. Look at line number 6: we declare the property stores as an Array of Store.</p><h3>Top level entities</h3><p>APIs tend to use a wrapper key so that the top level entity of the JSON is an object. Let’s suppose we’re requesting the available stores and we get this response:</p><pre>{<br>   &quot;stores&quot;:[<br>      {<br>         &quot;name&quot;:&quot;Gerry Cosby &amp; Co., Inc.&quot;,<br>         &quot;address&quot;:&quot;11 Pennsylvania Plaza, New York, NY 10001, United States&quot;,<br>         &quot;phone&quot;:&quot;+1 877-563-6464&quot;<br>      },<br>      {<br>         &quot;name&quot;:&quot;National Hockey League&quot;,<br>         &quot;address&quot;:&quot;1185 6th Ave, New York, NY 10036, United States&quot;,<br>         &quot;phone&quot;:&quot;+1 212-789-2000&quot;<br>      },<br>      {<br>         &quot;name&quot;:&quot;Modell&#39;s Sporting Goods&quot;,<br>         &quot;address&quot;:&quot;234 W 42nd St, New York, NY 10036, United States&quot;,<br>         &quot;phone&quot;:&quot;+1 212-764-7030&quot;<br>      }<br>   ]<br>}</pre><p>As you can see, the top level entity is the field stores which is an Array of Store. There’s nothing new here: we’ve just seen that in the section above. Here’s how we may deal with it:</p><pre>struct StoresList: Codable {<br>    let stores: [Store]<br>}</pre><p>That’s it.</p><p>But what if there’s no wrapper key? The JSON may look like this:</p><pre>[<br>   {<br>      &quot;name&quot;:&quot;Gerry Cosby &amp; Co., Inc.&quot;,<br>      &quot;address&quot;:&quot;11 Pennsylvania Plaza, New York, NY 10001, United States&quot;,<br>      &quot;phone&quot;:&quot;+1 877-563-6464&quot;<br>   },<br>   {<br>      &quot;name&quot;:&quot;National Hockey League&quot;,<br>      &quot;address&quot;:&quot;1185 6th Ave, New York, NY 10036, United States&quot;,<br>      &quot;phone&quot;:&quot;+1 212-789-2000&quot;<br>   },<br>   {<br>      &quot;name&quot;:&quot;Modell&#39;s Sporting Goods&quot;,<br>      &quot;address&quot;:&quot;234 W 42nd St, New York, NY 10036, United States&quot;,<br>      &quot;phone&quot;:&quot;+1 212-764-7030&quot;<br>   }<br>]</pre><p>Note that line 1 is not a curly brace: it’s a bracket, thus it’s an array. How we decode this? Very simple:</p><pre>let decoder = JSONDecoder()<br>if let stores = try? decoder.decode([Store].self, from: jsonData) {<br>    print(stores)<br>}</pre><p>Look at line 2: [Store].self is telling the decoder that the top level object is an Array of Store. Pretty neat, huh?</p><p>There’s another possible scenario that might give you the creeps. Take a look at this:</p><pre>[<br>   {<br>      &quot;Gerry Cosby &amp; Co., Inc.&quot;:{<br>         &quot;address&quot;:&quot;11 Pennsylvania Plaza, New York, NY 10001, United States&quot;,<br>         &quot;phone&quot;:&quot;+1 877-563-6464&quot;<br>      },<br>      &quot;National Hockey League&quot;:{<br>         &quot;address&quot;:&quot;1185 6th Ave, New York, NY 10036, United States&quot;,<br>         &quot;phone&quot;:&quot;+1 212-789-2000&quot;<br>      },<br>      &quot;Modell&#39;s Sporting Goods&quot;:{<br>         &quot;address&quot;:&quot;234 W 42nd St, New York, NY 10036, United States&quot;,<br>         &quot;phone&quot;:&quot;+1 212-764-7030&quot;<br>      }<br>   }<br>]</pre><p>Don’t panic! Let’s analyze it a little bit. Start reading from above: the JSON is an array with contains entities wrapped with different keys. So “Gerry Cosby…” wraps an address and a phone and so it does “National Hockey…” and “Model’s Sporting…” as well. Array of entities wrapped with a key.</p><p>Let’s create that entity first:</p><pre>struct Store: Codable {<br>    let address: String<br>    let phone: String?<br>}</pre><p>Each Store entity is wrapped with a key so that will look like String: Store, won’t it?</p><p>Now, we have all the stores listed in an array (look at lines 2 and 15). We express that by writing [String: Store].</p><p>But look at lines 1 and 16: the top level entity is an array as well (in this case with only one entry –[String: Store]– but an array it is), which gives us this structure: [[String: Store]].</p><p>Here’s how we decode it:</p><pre>let decoder = JSONDecoder()<br>if let stores = try? decoder.decode([[String:Store]].self, from: jsonData) {<br>    print(stores)<br>}</pre><p>We tell the decoder that our top level entity is of type [[String: Store]].</p><h3>Is that it?</h3><p>No. There’s much more. We’ll stop right here because it covers most of the common scenarios you may run into. But stay tuned because an advance series is coming soon.</p><h3>Now what?</h3><p>Start coding! Also you can bookmark my personal site, <a href="https://www.leandrofournier.com/">Swift Delivery</a>, and read this and other posts I’m writing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5faea0b19a1" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/working-with-json-in-swift-c5faea0b19a1">Working with JSON in Swift</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Documenting in Swift]]></title>
            <link>https://medium.com/@lean4nier/documenting-in-swift-e347f9c37dc0?source=rss-114f0eb90da9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e347f9c37dc0</guid>
            <category><![CDATA[markdown]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[infographics]]></category>
            <dc:creator><![CDATA[Leandro Fournier]]></dc:creator>
            <pubDate>Fri, 28 Jul 2017 15:12:27 GMT</pubDate>
            <atom:updated>2017-07-28T15:12:27.843Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*veAipMX0IN4X0ecPr6oO5w.png" /><figcaption><a href="http://blog.leandrofournier.com/swift/documentando-en-swift/">http://blog.leandrofournier.com/swift/documentando-en-swift/</a></figcaption></figure><p>We have no excuses: documenting our code has never been easier. Swift engineers have done an excellent job providing us with a pretty well known and easy way to keep our code documented: <a href="https://daringfireball.net/projects/markdown/">markdown</a> language. I’ve made an <a href="http://blog.leandrofournier.com/swift/documentando-en-swift/">infographic</a> to give you the most useful tips to achieve this. What follows is a brief overview.</p><p><em>All we need to know can be synthesized in two things: how to format and how Swift organizes and shows your documentation.</em></p><h4>How to format</h4><p>We can make use of almost any markdown syntax to format our documentation in our Swift code: predefined headings, strong, italics, bulleted lists, numbered lists, links, embedded code, etc.</p><h4>How Swift organizes and shows your documentation</h4><p>Swift organizes our methods’ documentation using the following sections, in this order (we just need to use the correct keywords to activate the optional ones):</p><ol><li>Description (default): here we can specify A LOT of things: author(s), copyright, warnings, notes, version, etc.</li><li>Parameters (optional)</li><li>Returns (optional)</li><li>Throws (optional)</li></ol><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drsYt3vPVCy_qKCe7sRLZA.png" /></figure><p>Then formatted documentation is shown when Option-click our method or selecting the interrogation mark in the Utilities bar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*Zt-yOOdCVJF-ZQA-arj3aA.png" /></figure><p>We can also separate our code with some comment tags:</p><ul><li>// MARK:</li><li>// TODO:</li><li>// FIXME:</li></ul><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FK3qLhfwilThOcnDwWHPSA.png" /></figure><p>This will be shown in the bar above our code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*dYkDy2qGVm4FzaLm5c8yUg.png" /><figcaption>Click where the function appears</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*TGSppZvipn8dznJs784TgA.png" /><figcaption>This navigation view will appear</figcaption></figure><h3>Bonus</h3><p>We can render our documentation in a beautiful way using <a href="https://github.com/realm/jazzy">Jazzy</a>.</p><p><em>Let’s be honest, everyone should do it for the sake of our team members or the future self that would get in touch with our own code in some months from now.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e347f9c37dc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>