<?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 Shakti Prakash on Medium]]></title>
        <description><![CDATA[Stories by Shakti Prakash on Medium]]></description>
        <link>https://medium.com/@shaktiprakash099?source=rss-b96c27963e19------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qp-fd0EZYeiBwwDh</url>
            <title>Stories by Shakti Prakash on Medium</title>
            <link>https://medium.com/@shaktiprakash099?source=rss-b96c27963e19------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 13:12:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shaktiprakash099/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[Let’s parse the JSON like a Boss with Swift Codable protocol]]></title>
            <link>https://medium.com/@shaktiprakash099/lets-parse-the-json-like-a-boss-with-swift-codable-protocol-3d4c4290c104?source=rss-b96c27963e19------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d4c4290c104</guid>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[parsing]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Shakti Prakash]]></dc:creator>
            <pubDate>Thu, 04 Oct 2018 14:16:57 GMT</pubDate>
            <atom:updated>2019-09-03T15:23:19.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7av1SecLHP0rLcl9Y8Iig.png" /></figure><h3>Over View</h3><p>In the world of iOS development handling, <strong>JSON</strong> has always been a tedious process for both new and experienced developers. Many programming tasks involve sending data over a network connection, saving data to disk, or submitting data to APIs and services. These tasks often require data to be encoded and decoded to and from an intermediate format while the data is being transferred.</p><p>There are few cool libraries out there like <a href="https://github.com/SwiftyJSON/SwiftyJSON">SwiftyJSON</a> which comes handy while parsing JSON.</p><h3>Swift Codable</h3><p>The Swift standard library also defines a standardised approach to data encoding and decoding. You adopt this approach by implementing the <a href="https://developer.apple.com/documentation/swift/encodable">Encodable</a> and <a href="https://developer.apple.com/documentation/swift/decodable">Decodable</a> protocols on your custom types. To support both encoding and decoding, declare conformance to Codable, which combines the <a href="https://developer.apple.com/documentation/swift/codable">Encodable</a> and Decodable protocols. This process is known as making your types codable. Let ‘s dive into this.</p><p>Take a look at an example of the first problem. Imagine you have the following JSON:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ef3a3668073c73798f2c259274c5ac9/href">https://medium.com/media/5ef3a3668073c73798f2c259274c5ac9/href</a></iframe><p>In the above code snippet our <strong>JSON</strong> consists of three keys — firstname, lastname, and age. So we created a structure with those keys. Adding Codable to the inheritance list for User triggers automatic conformance that satisfies all of the protocol requirements from Encodable and Decodable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*ngL3zTre80S5HF200bK0LA.gif" /><figcaption>Oh Its so simple</figcaption></figure><h3><strong>Scenario-1 (Bad Key naming )</strong></h3><p>Okay now have look on this example suppose our JSON will be like this :</p><pre>let json = “””<br>{<br>“first_name”: “shakti”,<br>“last_name”: “prakash”,<br>“age”:25<br>}<br>“””</pre><p>You’ll notice how the <strong><em>first_name</em></strong> and <strong><em>last_name</em></strong> keys in this JSON don’t make good constant names in Swift. What we want is <strong>firstName</strong> and <strong>lastName</strong>.</p><p>So how can we define a JSON object in Swift that represents this JSON but with proper Swifty constant names? Don’t worry <strong>JSONDecoder </strong>has one property called <strong><em>keyDecodingStrategy. </em></strong>By setting this property to .<strong>convertFromSnakeCase </strong>we can change snake-case keys to camel-case keys.</p><h4>keyDecodingStrategy</h4><p>This strategy follows these steps to convert <strong>JSON keys</strong> to camel-case:</p><ol><li>Capitalize each word that follows an underscore.</li><li>Remove all underscores that aren’t at the very start or end of the string.</li><li>Combine the words into a single string.</li></ol><p>The following examples show the result of applying this strategy:</p><p>user_id Converts to: userId</p><p>base_uri Converts to: baseUri</p><p>Here is the code snippet:</p><pre>import Foundation<br>import UIKit</pre><pre>let json = “””<br>{<br>“first_name”: “shakti”,<br>“last_name”: “prakash”,<br>“age”:25<br>}<br>“””</pre><pre>let jsonData = Data(json.utf8)</pre><pre>struct User:Codable {<br> var firstName:String<br> var lastName:String<br> var age:Int<br>}</pre><pre>let decoder = JSONDecoder()<br>decoder.keyDecodingStrategy = .convertFromSnakeCase</pre><pre>do {<br> let response = try decoder.decode(User.self, from: jsonData)<br> print(response)<br>} catch {<br> print(“Parsing Failed”)<br>}</pre><h4><strong>CodingKeys</strong></h4><p>We can also achieve this by using enum called <strong>CodingKeys,</strong> as explained in the Solution section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*NQBIQLwN6PY_qqFsyroHvw.png" /></figure><h3>Scenario-2 (Absence of any key or Null Data)</h3><p>Consider the below case the responding keys in JSON might or might not be present or may be null. You will need to implement the init(from decoder: Decoder) throws function and place your specific logic there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*eOdFCVgJH5BW89vYcN1sZg.png" /><figcaption><strong>address </strong>key is null here</figcaption></figure><p>Suppose you added an address field to your Swift model object:</p><pre><strong>struct Person</strong>: Codable{ <br><strong>let </strong>firstName: String<br><strong>let </strong>lastName: String<br><strong>let </strong>age: Int<br><strong>let </strong>address: String</pre><pre><strong>private enum CodingKeys</strong>: String, CodingKey{ <br> <strong>case </strong>firstName = “first_name”<br> <strong>case </strong>lastName = “last_name”<br> <strong>case </strong>age<br> <strong>case </strong>address<br> }</pre><pre>}</pre><p>If you provided the same JSON as before and tried to decode it into an instance of a Person with the newly added address field, JSONDecoder would throw an error because this field is missing from the JSON and is not defined as optional in the model. To solve this problem, implement the init(from decoder: Decoder) throws function from Decodable and place logic there that fills in the default value for the address field:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c38a5e8dc4f84bf36751c0b88146b476/href">https://medium.com/media/c38a5e8dc4f84bf36751c0b88146b476/href</a></iframe><p>So by using <strong><em>decodeIfPresent </em></strong>we can Decodes a value of the given type for the given key, if present. This method returns `nil` if the container does not have a value associated with `key`, or if the value is null.</p><h3>Scenario -3 (Unpredictable Datatype of the Key )</h3><p>Codable protocol really helps us a lot while parsing JSON. But the real problem occurs when it comes to handling a key whose data type is unpredictable — it may be a string or maybe Int. Consider the following example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5nJA791GUtSGzxwAeTAbmA.png" /></figure><p>Our JSON above consists of one Array with two elements. The first element Age is <strong>Int</strong> type while the second element age is <strong>String</strong> Type.</p><p>If you follow such an approach for decoding, Xcode will throw you an Error. So first, we have to change our datamodel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*LUGCAlAtjYSJqpdEzrXHTQ.png" /></figure><p>Here we defined age as <strong>VariacType</strong>. Here <strong>VariacType</strong> is an <em>enum</em> which has two cases one for Int and other one is for String. You can customize as you wish. And the <strong>VariacType</strong> enum is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*vj2e6WQdmKI1hYhf4bUT-A.png" /></figure><p>To access the value I have created extension of that:</p><pre>extension VariacType {<br> var Value:String {<br> switch self {<br> case .int(let intvalue):<br> return String(intvalue)<br> case .string(let stringValue):<br> return stringValue<br>  }<br> }<br>}</pre><p>And here comes the complete <a href="https://gist.github.com/shaktiprakash099/f7424d6c51ac886f10cebd6afeb36bcd">Gist File</a>, which you can take a look at. I hope it may help you.</p><h3>Conclusion</h3><p>From this article, we learned how to use Swift Codable protocol while creating our JSON model of the response. We also looked at using different kinds of <strong>keyDecodingStrategies</strong> and deal with dynamic responses (i.e if JSON contains null value or different data type).</p><p>Happy Coding! <br><a href="https://about.me/shaktiprakash099">Shakti Prakash</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d4c4290c104" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing Around with Closures in Swift- 4 (Part -2)]]></title>
            <link>https://medium.com/@shaktiprakash099/playing-around-with-closures-in-swift-4-part-2-7f78a2897dd6?source=rss-b96c27963e19------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f78a2897dd6</guid>
            <category><![CDATA[swift-4]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift-playgrounds]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Shakti Prakash]]></dc:creator>
            <pubDate>Fri, 21 Sep 2018 11:58:48 GMT</pubDate>
            <atom:updated>2018-09-21T12:04:31.997Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apXhEl5f3wwTKH4fQYMExA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/q2GNdFmhxx4?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Rich Tervet</a> on <a href="https://unsplash.com/search/photos/development?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Hello Everyone !! In the previous article we all discussed about few basic closures in Swift.If you haven’t checked it kindly check <a href="https://medium.com/@shaktiprakash099/playing-around-with-closures-in-swift-4-part-1-ae2665ca49ac"><strong>this</strong></a> out .In this Tutorial we will discuss about few more .</p><p>Swift automatically provides shorthand argument name to inline closures ,which can be used to refer to the values of the closure’s arguments by their names $0,$1,$2 and so on.</p><h3>Shorthand Argument Names</h3><p>As we discussed above Swift 4 facilitates the user to represent Inline closures as shorthand argument names by representing $0, $1, $2 — — $n.By using this Shorthand argument names inside our closures expression we can omit the closure’s argument list from its definition .The <strong><em>in</em></strong><em> keyword</em><strong><em> </em></strong><em>can be omitted because the closure expression is made up entirely of its body.Have a look at the following example .</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlfI2loaPA5AIM7bmncSRQ.png" /></figure><p>So in the first example a closures is created which takes a single parameter and returns a string .here $0 refers to the first parameters .Similarly in the second examples the closures takes two parameters and by using $1 we are referring to the second arguments in the closure</p><h3>Autoclosures</h3><p>We know that closure can be used as the parameters in a functions .when we write <strong><em>@autoclosure</em></strong> the argument automatically gets wrapped in a closure .But there is one problem with this if we create a function which has <strong><em>@autoclosure </em></strong>then It’s common to <em>call</em> that functions that take autoclosures, but it’s not common to <em>implement </em>that kind of function. .Lets take a small example .</p><pre>func simpleFunctionwithoutAutoclosure(_ parameters:()-&gt;Void){<br> print(“hey we just created a function without @autoclosure attributes “)<br> parameters()<br>}<br>simpleFunctionwithoutAutoclosure ({<br> print(“hello”)<br>})</pre><pre>func simpleFunctionwithAutoclosure(_ parameters:@autoclosure()-&gt;Void){<br> print(“hey we just created a function with @autoclosure attributes “)<br> parameters()<br>}</pre><pre>simpleFunctionwithAutoclosure(print(“hii”))</pre><p>And the Out put is as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*4MObr3GWHoMIHoH7FhTiXg.png" /></figure><p>From the above two functions we have noticed that we don’t need to wrap the expression in curly braces in case of @autoclosure. That is what we would need to do if we were to pass in a closure instead of an autoclosure.</p><h3>Escaping Closures</h3><p>A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write <a href="http://twitter.com/escaping">@escaping</a> before the parameter’s type to indicate that the closure is allowed to escape.</p><p><a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID546">Apple’s docs</a> give an example of appending a closure that’s passed into a function to a mutable array of closures within your class/struct:</p><pre>var completionHandlers: [() -&gt; Void] = []</pre><pre>func someFunctionWithEscapingClosure(completionHandler: <a href="http://twitter.com/escaping">@escaping</a> () -&gt; Void) {<br> completionHandlers.append(completionHandler)<br>}</pre><p>As we can see, this follows the</p><p>1. Pass closure,</p><p>2. someFunctionWithEscapingClosure returns,</p><p>3. Closure executed</p><p>If we didn’t mark the parameter of this function with <a href="http://twitter.com/escaping">@escaping</a>, we would get a compile-time error.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f78a2897dd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing Around with Closures in Swift- 4 (Part -1 )]]></title>
            <link>https://medium.com/@shaktiprakash099/playing-around-with-closures-in-swift-4-part-1-ae2665ca49ac?source=rss-b96c27963e19------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae2665ca49ac</guid>
            <category><![CDATA[swift-4]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[playground]]></category>
            <dc:creator><![CDATA[Shakti Prakash]]></dc:creator>
            <pubDate>Thu, 20 Sep 2018 13:42:40 GMT</pubDate>
            <atom:updated>2018-09-21T12:03:39.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*zwm6dtYTWSlXlGRsoCxc3g.png" /></figure><p><em>According to </em>the swift programming language</p><blockquote><em>Closures</em> are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.</blockquote><p>In simple term closures are functions having no name .They simply capture and store reference to any constants and variables from the context in which they are defined .<em>This is known as closing over those constants and variables.</em></p><h3><strong>Closure Expression Syntax</strong></h3><blockquote><strong>{ ( parameters) -&gt; return type in</strong></blockquote><blockquote><strong>statements</strong></blockquote><blockquote><strong>}</strong></blockquote><p>Let’s start with a simple closure which prints a message</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*B7l8jB1XgE8U8n8ZJgYtxQ.png" /></figure><p>In the above example a simple closure is created and assigned to <strong>myfirstClosure</strong> .We can also say that a function with no name is created and we can call it like a normal function.</p><pre>myfirstClosure()</pre><h3><strong>Closures with parameters</strong></h3><p>Closures can accept parameters .To make the closure accept parameters we have to list them inside parentheses and then we have to write <strong><em>in </em></strong><em>keyword</em><strong><em> </em></strong><em>So that the closure main body can be started after this .And the example of closures with parameters is as follows .</em></p><pre><em>let myfirstClosure = { (withParameter : String) in<br> print(“Finally i created my first Closure with \(withParameter)”)<br>}</em></pre><pre><em>myfirstClosure(“firstparameters”)</em></pre><p>and the out put will be</p><blockquote>Finally i created my first Closure with firstparameters</blockquote><h3><strong>Closures with returning value</strong> type</h3><p>Closures can also return value .So to make our closure return value we have to do little modification in our closure with parameters like Syntax .After listing the parameters in side parentheses we have to write <strong><em>-&gt;datatype </em></strong>followed by<strong><em> In </em></strong>Keyword and lastly use <strong><em>return</em></strong> just like normal functions .And the example is as follows .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDlrRhzMkUgN4J4JFbwQTQ.png" /></figure><h3><strong>Closure as Parameters :-</strong></h3><p>We can also pass a closure like a parameter of a function just like how we pass string or integers as parameters of a function .But while doing so we have to do few things in the syntax .As we define each parameters type inside a function so a when a closure is used as parameters inside a function so we need to specify the Closure (parameter ) type as <strong><em>()-&gt;datatype </em></strong>if we are returning nothing we can simple changed above syntax as <strong><em>()-&gt;Void. </em></strong>here void mean nothing .And example is defined as below</p><pre>import UIKit</pre><pre>let closure = {<br> print(“I am a simple closure “)<br>}</pre><pre>func simplefunctionWithClosures(closure:()-&gt;Void){<br> print(“Call the Closure”)<br> closure()<br> print(“Closure is called which is  used as parameter of the function “)<br>}</pre><pre>simplefunctionWithClosures(closure: closure)</pre><p>And the output is here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*6GbET9csIV1sAfML6sdNrg.png" /></figure><h3>Trailing Closures</h3><p>When we need to pass a closure expression to a function as the function final argument and the closure expression too long it can be useful to write it as a trailing closures .A trailing closure is written after the function call’s parentheses, even though it is still an argument to the function.When we use the trailing closure syntax, we don’t write the argument label for the closure as part of the function call.Here is what swift official doc says .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*WSDDBVntudGUXL0QXfj8-A.png" /></figure><p>We will discuss some more about this in <a href="https://medium.com/@shaktiprakash099/playing-around-with-closures-in-swift-4-part-2-7f78a2897dd6">this</a> articles .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae2665ca49ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>