<?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 Shiva Ram Reddy on Medium]]></title>
        <description><![CDATA[Stories by Shiva Ram Reddy on Medium]]></description>
        <link>https://medium.com/@kathishivaram?source=rss-9db66e72b827------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r477goaD5hWZ_Da3fmdQ7Q.jpeg</url>
            <title>Stories by Shiva Ram Reddy on Medium</title>
            <link>https://medium.com/@kathishivaram?source=rss-9db66e72b827------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:50:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kathishivaram/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[Single Responsibility Principle(SRP)]]></title>
            <link>https://kathishivaram.medium.com/single-responsibility-principle-srp-523d93a8d4a4?source=rss-9db66e72b827------2</link>
            <guid isPermaLink="false">https://medium.com/p/523d93a8d4a4</guid>
            <category><![CDATA[single-responsibility]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Shiva Ram Reddy]]></dc:creator>
            <pubDate>Sun, 28 Feb 2021 06:47:10 GMT</pubDate>
            <atom:updated>2021-02-28T06:47:10.453Z</atom:updated>
            <content:encoded><![CDATA[<h3>Single Responsibility Principle</h3><blockquote>SRP states that <strong>every component should have one and only one responsibility</strong>. Lets decode this by understanding what exactly is a <strong>responsibility</strong>.</blockquote><h4>What is a Responsibility ?</h4><p>Let’s break some <strong>misconceptions</strong> regarding responsibility!</p><p>To conform to SRP a class, struct or enum(<strong>Component</strong>) should have a single method, (this component may conform to SRP by only having one method) but this is not the <strong>end goal</strong>.</p><blockquote><strong>Example</strong> :-</blockquote><p>To fulfil one responsibility we might have more than one method/function. We breakdown big methods, into multiple methods to make it more readable, that doesn’t mean it has multiple responsibilities.</p><p>The idea is not to create <strong>one function</strong> per <strong>component</strong>, rather it is to fulfil one responsibility.</p><p>It is hard to define what exactly responsibility is, because it depends on requirements, stakeholder involved and how the domain we are working on is defined. <strong><em>But there is simple guideline for identifying if a component is fulfilling SRP</em></strong><em>.</em></p><blockquote><strong>Guideline</strong></blockquote><p>How many <strong>reasons</strong> does the component has to <strong>change</strong> for.</p><p>If it has more than one reason for change, it is probably fulfilling more than one responsibility, which is indication that it needs to be broken down into more components/types.</p><blockquote><strong>Why do we need to care about this</strong></blockquote><p>When you have components which fulfils SRP each, then they lead to codebase which is</p><ul><li>Composable, different components can be composed together for a functionality</li><li>Can be implemented in isolation.</li><li>Can be tested in isolation.</li><li>Reusable</li></ul><p>Ultimately leads to a codebase which is <strong>modular</strong> in nature.</p><h4><strong>Lets take a look at a example</strong></h4><p>We have been given task to implement <strong>ImageCaching</strong> for our app.</p><p><strong>ImageCaching</strong> deals with</p><p>1.<strong>Adding</strong><br>2.<strong>Retrieving</strong> <br>3.<strong>Deleting</strong></p><p>image from memory.</p><p>We implement ImageCacheManager to handle above operations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e2a97e738be1de1cd7d2b3fa0f4dd91/href">https://medium.com/media/2e2a97e738be1de1cd7d2b3fa0f4dd91/href</a></iframe><p>This certainly has more than one behaviour and corresponding functions, does this means it violates SRP.</p><p>No, It does not in this context, <strong>ImageCacheManager</strong> is performing three different operation but its <strong>only responsibility</strong> is to <strong>manage ImageCache</strong>.</p><p>Now a new requirement comes up, which is to delete cache older than specific number days (for example 7 days), upon retrieval. Simplest way to do this is to add validation logic inside retrieval method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96a5820f72afe0f80d06ebd4dcf6cec6/href">https://medium.com/media/96a5820f72afe0f80d06ebd4dcf6cec6/href</a></iframe><p>After adding <strong>validateCache()</strong> method to <strong>ImageCacheManager</strong> did we violate SRP.</p><p>Lets go back to guideline, which says to look for how many reasons does the component has to change for.</p><p>Component has to change for managing cache responsibility for example if team decides use different persistence mechanism(User Defaults, Core Data, Realm etc), <br>But in addition to that component also has to change when <strong>validation policy</strong> changes.</p><p>This certainly violates SRP!</p><blockquote><strong>How do we fix it </strong>?</blockquote><p>We can create a separate component/type for <strong>validation</strong> i.e <strong>ImageCacheValidator</strong> whose responsibility is to <strong>validate cache</strong>.</p><p>This way we separate <strong>Validation</strong> and <strong>Managing Cache</strong>, which are two separate responsibility into separate component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c34718450d1f9491358366bf88f55016/href">https://medium.com/media/c34718450d1f9491358366bf88f55016/href</a></iframe><p>In future if we want to change how we store cache use Core Data, Realm or anything related to <strong>ImageCaching</strong> , we can do it separately from <strong>Validation</strong>. Same goes to validation, it can changes in isolation from CacheManager.</p><blockquote><strong>Conclusion</strong></blockquote><p>If we follow SRP, by separating code into single purpose components/types subsequent changes in one component won’t affect other component.<br>We end up with small components which are easy to maintain and understand.</p><h4>Learning Outcomes</h4><ol><li>What is Single Responsibility Principle.</li><li>Why SRP is important.</li></ol><p>Thats it folks, See you in another article soon 🙋‍♂️.</p><p><strong>References</strong></p><ol><li>youtube.com/watch?v=FA1uUGZcN2U&amp;ab_channel=EssentialDeveloper(Essential Developer Youtube Video)</li></ol><p>2.Clean Architecture — Robert C Martin</p><p>If you would like to suggest some changes to the article feel free to reach me at <strong>kathishivaram@gmail</strong> or comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=523d93a8d4a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delegation in Swift]]></title>
            <link>https://kathishivaram.medium.com/delegation-in-swift-2e82c64c647d?source=rss-9db66e72b827------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e82c64c647d</guid>
            <category><![CDATA[design-pattern-ios]]></category>
            <category><![CDATA[delegate-protocol]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[delegate]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Shiva Ram Reddy]]></dc:creator>
            <pubDate>Wed, 17 Feb 2021 15:00:35 GMT</pubDate>
            <atom:updated>2021-02-18T19:31:09.444Z</atom:updated>
            <content:encoded><![CDATA[<p>Delegation is a way through which one instance in a program acts on a behalf of other. It lets you delegate down some of the responsibilities, without actually knowing the concrete type behind(Thanks to <strong>Protocols</strong> 🤝).</p><p>It is a very simple and powerful pattern among plethora of design patterns available to us! and chances are that you might have already used it in iOS development(hint:- TableView, TextField 🥱). So what will we be doing today, lets take a look at behind the scene of delegate pattern and implement it on our own example.</p><h3>What is Delegation ?</h3><p><em>Delegation</em> is a design pattern that enables a class or structure to hand off (or <em>delegate</em>) some of its responsibilities to an instance of another type. — Apple Docs</p><p>Lets understand this with a example :-</p><p>Now to make it interesting, lets make you a mobile manufacturer, who has built a powerful mobile and now wants to sell it to people.</p><p>There are two tasks which needs to be accomplished</p><p>1- Making the mobile</p><p>2- Selling the mobile (later sit back and count the 🤑)</p><p>As a manufacturer your task is to build the mobile, but how would you sell it, At this point your company board decides to steps in and decides to delegate this responsibility to a <strong>seller(the delegate)</strong>.</p><p>Time for real action, open your playground, lets build the mobile and sell :-</p><p>Mobile representation using a data model</p><pre><strong>struct</strong> Mobile {</pre><pre><strong>   let</strong> screenSize: Int<br>   <strong>let</strong> processor: String<br>   <strong>let</strong> operatingSystem: String<br>   <strong>let</strong> name: String<br>}</pre><p>Lets build Mobile Manufacturer, who can build mobile</p><pre><strong>class</strong> MobileManufacturer {</pre><pre><strong>func</strong> buildMobile() {<br>        <br>         <strong>let</strong> mobile = Mobile(screenSize: 6<br>                             , processor: &quot;A3&quot;<br>                             , operatingSystem: &quot;iOS&quot;<br>                             , name: &quot;iPhone Classic&quot;)<br>    }<br>}</pre><p>so finally the time has come to sell the mobile, as the company board decided that it would be beneficial for all, If we delegate this task to a seller who can do it better.</p><p>So we need a seller whose responsibility is to sell the mobile, As there might be many seller out in the market we need a seller to whom we can communicate and have established a contract. (Technically speaking, the seller should be confirming to <strong>Protocol</strong> which defines <strong>delegated responsibilities</strong>)</p><p>For this we use protocol,</p><p>Delegate design pattern is implemented by defining a protocol that <strong>encapsulates the delegated responsibilities</strong>, such that a conforming type (known as a delegate) is guaranteed to provide the functionality that has been delegated.</p><pre><strong>protocol</strong> MobileSellerDelegate {</pre><pre><strong>func</strong> sellMobile(mobile: Mobile)<br>}</pre><p>Now we have found a seller who is ready to confirm to this delegate and provide us with required functionality</p><pre><strong>class</strong> MobileSeller: <strong>MobileSellerDelegate</strong> {<br>    <br>    <strong>func</strong> sellMobile(mobile: Mobile) {<br>         <br>         print(&quot;I will take care from here now&quot;)<br>    }<br>}</pre><p>We add delegate to MobileManfacturer, so that manufacturer can delegate the task of selling the mobile as soon as the mobile is ready</p><p>How do we do it ?</p><p>1.We add a delegate property to the class whose type is same as the Protocol to which seller confirms to.</p><p>2.There is a possibility of creating retain cycle, so we make it weak</p><pre><strong>class</strong> MobileManufacturer {</pre><pre><strong>weak</strong> <strong>var</strong> sellerDelegate: MobileSellerDelegate?</pre><pre><strong>func</strong> buildMobile() {<br>        <br>         <strong>let</strong> mobile = Mobile(screenSize: 6<br>                             , processor: &quot;A3&quot;<br>                             , operatingSystem: &quot;iOS&quot;<br>                             , name: &quot;iPhone Classic&quot;)</pre><pre>         sellerDelegate?.sellMobile(mobile: newIphone)<br>    }<br>}</pre><p>Let put everything into action now</p><pre>let seller = MobilerSeller()<br>let mobileManufacturer = MobileManufacturer()</pre><pre>//Setting the seller delegate to MobileSeller instance<br>mobileManufacturer.sellerDelegate = seller</pre><pre>//Calling buildMobile() method which would after making mobile delegate the task of selling to seller instance<br>mobileManufacturer.buildMobile()</pre><p>Thats it !!! 😃</p><p>Why to Delegate ?</p><ol><li>Delegate allows you write code which is not coupled, Client has no idea about the concrete type behind the protocol, you can change delegate pattern and now some other instance will be handling the delegated task.</li><li>Delegate is useful for 1 to 1 communication, If your goal is to only have this type of communication, delegate is better approach than Notification(1 to Many), or other design pattern</li></ol><p>Learning Outcomes</p><ol><li>What is Delegate Design Pattern</li><li>Create and use custom Delegate design pattern</li></ol><p>Thats it folks, See you in another article soon 🙋‍♂️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e82c64c647d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inheritance , Polymorphism And Overriding in swift]]></title>
            <link>https://medium.com/swift-ios/inheritance-polymorphism-and-overriding-in-swift-b928b744921d?source=rss-9db66e72b827------2</link>
            <guid isPermaLink="false">https://medium.com/p/b928b744921d</guid>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[overriding]]></category>
            <dc:creator><![CDATA[Shiva Ram Reddy]]></dc:creator>
            <pubDate>Sat, 06 Jul 2019 13:40:43 GMT</pubDate>
            <atom:updated>2019-07-06T13:40:43.608Z</atom:updated>
            <content:encoded><![CDATA[<h3>Inheritance , Polymorphism And Overriding in swift</h3><p><strong>Inheritance</strong></p><p>Lets understand inheritance through example</p><pre>class Person {</pre><pre>    var firstName: String<br>    var lastName: String</pre><pre>    init(firstName:String, lastName:String) {</pre><pre>         self.firstName = firstName<br>         self.lastName = lastName</pre><pre>    }<br>}</pre><pre>class Student {</pre><pre>    var firstName: String<br>    var lastName: String<br>    var course: String</pre><pre>    init(firstName:String, lastName:String) {</pre><pre>         self.firstName = firstName<br>         self.lastName = lastName<br>    }<br>}</pre><p>We can see that there’s lot of code duplication between Person and Student, it shows us there is relationship between student and person i.e<strong><em> student is a person</em></strong>.Inheritance helps represent this kind of relationship.</p><p>A class can <em>inherit</em> methods, properties, and other characteristics from another class. When one class inherits from another, the inheriting class is known as a <strong><em>subclass</em></strong>, and the class it inherits from is known as its <strong><em>superclass</em></strong>.</p><p>Lets re write the above example using inheritance</p><pre>class Person { .  // base class or super class</pre><pre>    var firstName: String<br>    var lastName: String</pre><pre>    init(firstName:String, lastName:String) {</pre><pre>         self.firstName = firstName<br>         self.lastName = lastName<br>    <br>    }<br>}</pre><pre>class Student : Person { // subclass</pre><pre>    var course: String</pre><pre>    init(firstName:String, lastName:String , course: String) {</pre><pre>         self.course = course<br>         super.init(firstName: firstName, lastName: lastName)<br>    }</pre><pre>}</pre><p>Now Student class inherits from Person, through inheritance student automatically gets properties and method declared in the Person class.Additionally Student object will have all the properties defines in the subclass i.e course is instance property of Student not Person.</p><p>A swift class can only inherit from one class which is known as single inheritance but there is no limit for depth of subclassing.</p><p><strong>Polymorphism</strong></p><p>As classes support inheritance , they bring a new feature known as polymorphism i.e ability of object to take many form.</p><p>Lets understand this with an example</p><pre>class Person { // base class</pre><pre>   var name: String</pre><pre>   init(name: String) {</pre><pre>       self.name = name<br>    }</pre><pre>   func getInformation() -&gt; String {</pre><pre>       return &quot;My name is \(name) &quot;<br>    }<br>}</pre><pre>class Employee : Person {</pre><pre>   var employer: String</pre><pre>   init(name: String, employer: String) {</pre><pre>       self.employer = employer<br>       super.init(name: name)<br>   }</pre><pre>   override func getInformation() -&gt; String {</pre><pre>       return &quot;My name is \(name) and work for \(employer)&quot;<br>   }<br>}</pre><pre>class Student : Person {</pre><pre>   var college: String</pre><pre>   init(name: String, college: String) {</pre><pre>        self.college = college<br>        super.init(name: name)<br>   }</pre><pre>   override func getInformation() -&gt; String {</pre><pre>        return &quot;My name is \(name) and study at \(college)&quot;<br>   }<br>}</pre><p>In the above example student and employee inherit from person. Because of that any instance of those two classes contain all the properties of Person , and instance of Student/Employee can be treated as instance of Person also.</p><pre>var john = Employee(name: &quot;John&quot;, employer: &quot;ABC&quot;)</pre><pre>var shiva = Student(name: &quot;Shiva&quot;, college: &quot;XYZ University&quot;)</pre><pre>var allPersons : [Person] = [john, shiva]</pre><p>Even though “allPersons” is array of Person , we have put inside it instance of Employee and Student .This is possible because of polymorphism.An object can work as its class and its parent classes, all at the same time.</p><pre>func searchInPhoneBook(_ person: Person) -&gt; String {</pre><pre>    return &quot;\(person.name)&quot;<br>}</pre><pre>let john = Employee(name: &quot;John&quot;, employer: &quot;ABC&quot;)<br>let shiva = Student(name: &quot;Shiva&quot;, college: &quot;XYZ University&quot;)</pre><pre>searchInPhoneBook(john) . // prints John<br>searchInPhoneBook(shiva) . // prints shiva</pre><p>As john and shiva derives from Person, they are valid input into function which has argument type of Person.It can only observe the elements of Employee/Student that are defined in the Person base class.This is possible because of polymorphism.</p><p><strong>Overriding</strong></p><p>A subclass can provide its own implementation for properties or methods which it has inherited this is known as overriding.</p><p>When you override a property or method you can still access its super class implementation using “super ” keyword on the superclass property or method.</p><pre>class Animal {</pre><pre>     func makeNoise() {<br>    // does nothing because an arbitrary vehicle does not make sound </pre><pre>     }<br>}</pre><pre>class Dog : Animal {</pre><pre>    override func makeNoise() {<br>        print(&quot;bow bow&quot;)<br>    }</pre><pre>}<br></pre><p>As Dog makes sound , it overrides its superclass method and provides its own implementation.</p><p>Where to go from here: I have covered basics of the above mentioned topics , you are good to get started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b928b744921d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-ios/inheritance-polymorphism-and-overriding-in-swift-b928b744921d">Inheritance , Polymorphism And Overriding in swift</a> was originally published in <a href="https://medium.com/swift-ios">Swift Programming &amp; iOS Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Initialization in Swift — Part 1]]></title>
            <link>https://medium.com/swift-ios/initialization-in-swift-part-1-f2e8b25d0dab?source=rss-9db66e72b827------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2e8b25d0dab</guid>
            <category><![CDATA[initialization]]></category>
            <category><![CDATA[convenience-initializer]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[two-phase-initialization]]></category>
            <category><![CDATA[designated-initializer]]></category>
            <dc:creator><![CDATA[Shiva Ram Reddy]]></dc:creator>
            <pubDate>Thu, 04 Jul 2019 10:26:08 GMT</pubDate>
            <atom:updated>2019-07-04T11:59:46.008Z</atom:updated>
            <content:encoded><![CDATA[<h3>Initialization in Swift</h3><blockquote><em>Introduction, Default Initialization , Designated and Convenience initializers.</em></blockquote><p>Initialization is the process of setting initial value of stored properties on that instance (stored properties cannot be left in an indeterminate state).This is done through special method known as <strong>init()</strong>.Swift initializers do not return a value.</p><p><strong>Setting initial values on stored properties</strong></p><p>The main objective is classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created.</p><pre>struct Book {</pre><pre>   var title: String</pre><pre>   init() { </pre><pre>       self.title = &quot;How to initialize&quot;</pre><pre>   }<br>}</pre><pre>var book1 = Book() </pre><pre>print(book1.title) // &quot;How to initialize&quot;</pre><p>In the above example Book has a stored property title which is being set to initial value of “How to initialize” at the time of instance creation by init() method.It ensure that new instances of a type are correctly initialized before they are used for the first time i.e ( print(book1.title) )</p><p>Initial value on stored property can also be assigned at the point of declaration of variable or constant</p><pre>struct Book {</pre><pre>    var title: String = &quot;Initial value assigned at declaration&quot;<br>}</pre><p><strong>Customizing Initialization</strong></p><p>Initialization can be customized by providing input parameters</p><pre>class Book {</pre><pre>    var title: String<br>    var author: String<br>    var course: String</pre><pre>    init(title: String, author: String, course: String) {</pre><pre>        self.title = title<br>        self.author = author<br>        self.course = course</pre><pre>    }</pre><pre>}</pre><pre>let book1 = Book(title: &quot;Init()&quot;, author: &quot;Shiva&quot;, course: &quot;swift&quot;)<br></pre><p>The above example defines class Book which stores title, author, course. It implements an initializer “init(title: String, author: String, course: String)” , which initializes new instance with values provides during instance creation.</p><p>The names and types of an initializer plays an important role in identifying which initializer should be called</p><pre>class Book {</pre><pre>    var title: String<br>    var author: String<br>    var course: String</pre><pre>    init(title: String, author: String, course: String) {</pre><pre>        self.title = title<br>        self.author = author<br>        self.course = course</pre><pre>    }</pre><pre>    init(title: String, author: String) {</pre><pre>        self.title = title<br>        self.author = author<br>        course = &quot;obj-c&quot;</pre><pre>    }</pre><pre>}</pre><p>Both initializers can be used to create a new Book instance, by providing named values for each initializer parameter:</p><pre>let book1 = Book(title: &quot;Init()&quot;, author: &quot;Shiva&quot;, course: &quot;swift&quot;)<br>let book2 = Book(title: &quot;New Init&quot;, author: &quot;Ram&quot;)</pre><p><strong>Default Initializers</strong></p><p>Swift provides a default initializer for any structure or classes given all stored properties have been set to values and does not provide any initializer.The default initializer creates new instance with default values provided at the time of class or structure creation.</p><pre>class Cricketer {</pre><pre>    var name = &quot;Rahul Dravid&quot;<br>    var active = false</pre><pre>}</pre><pre>var player = Cricketer()</pre><p>As all the properties of Cricketer have default values , it gains a default initializer that creates a new instance with all of its properties set to default values.</p><p>Structure receives <strong><em>memberwise initializer </em></strong>if they don’t define any custom initializer of its own.it receives memberwise initializer even if none of its properties are set.</p><pre>struct Vehicle {</pre><pre>    var type: String<br>    var numberOfWheels: Int<br>    var brand: String</pre><pre>}</pre><pre>let bicycle = Bicycle(type: &quot;Bicycle&quot;, numberOfWheels: 2, brand: &quot;KAO&quot;)</pre><p>Structure vehicle received memberwise initializer , as it did not have any custom initializer (does not matter if properties are set or not).</p><h4><strong>Initializer Delegation for Value Types</strong></h4><p>Initializer can call other initializer to perform part of initialization, this process is known as initializer delegation. As Value types (structure ) do not support inheritance , initializers in struct can delegate to other initializer that struct provides.</p><p>self.init is used to refer to other initializers from the same value type when writing your own custom initializers. You can call self.init only from within an initializer.</p><pre>struct Size {</pre><pre>    var width = 0.0 <br>    var height = 0.0</pre><pre>}</pre><pre>struct Point {</pre><pre>    var x = 0.0<br>    var y = 0.0</pre><pre>}</pre><pre>struct Rect {</pre><pre>    var origin = Point()<br>    var size = Size()</pre><pre>}</pre><p>The above example defines custom Rect structure , which require two supporting structures Size and Point both of which provide default value , Sales instance can be initialized as following :-</p><pre>struct Rect {</pre><pre>   var size = Size()<br>   var origin = Point()</pre><pre>   init() {<br>  //This initializes Rect with Size (0.0, 0.0) and Origin (0.0, 0.0)<br>   }</pre><pre>   init(size: Size, origin: Point) {</pre><pre>    self.size = size<br>    self.origin = origin<br>    // This initializes Rect with custom values provided at the       time of initialization.</pre><pre>  }</pre><pre>   init(size: Size, center: Point) {</pre><pre>    let originX = center.x - (size.width / 2)<br>    let originY = center.y - (size.height / 2)</pre><pre>    self.init(origin: Point(x: originX, y: originY), size: size)<br>    //This initializer user initializer delegation to call initializer with origin as parameter after origin is calculated from center</pre><pre>   }</pre><pre>}</pre><pre>let customRect = Rect(size: Size(width: 5.0, height: 5.0), origin: Point(x: 2.0, y: 2.0)</pre><pre>let derivedCustomRect = Rect(size: Size(width: 4.0, height: 4.0), center: Point(x: 2.0, y: 2.0)</pre><p><strong>Class Initialization</strong></p><p>As class supports inheritance , all the stored properties including any properties the class inherits from its super class must be assigned an initial value during initialization</p><p>Swift provides two kinds of initializers for class type</p><ol><li>Designated Initializer</li><li>Convenience Initializer</li></ol><p><em>Designated initializers</em> are the primary initializers for a class. A designated initializer fully initializes all properties introduced by that class and calls an appropriate superclass initializer to continue the initialization process up the superclass chain.</p><blockquote><em>Every class must have at least one designated initializer</em></blockquote><p>Designated initializers are written as same as the normal initializer:-</p><pre>init(parameters) {</pre><pre>     statements</pre><pre>}</pre><p><em>Convenience initializers are secondary, supporting initializers for a class. You can define a convenience initializer to call a designated initializer from the same class as the convenience initializer with some of the designated initializer’s parameters set to default values. You can also define a convenience initializer to create an instance of that class for a specific use case or input value type. — apple docs</em></p><p>Convenience initializers are written in the same style, but with the convenience modifier placed before the init keyword</p><pre>convenience init(parameters) {</pre><pre>statements</pre><pre>}</pre><p>Lets see an example</p><pre>class Book {</pre><pre>    var title: String<br>    var author: String<br>    var course: String</pre><pre>    init(title: String, author: String, course: String) {</pre><pre>        self.title = title<br>        self.author = author<br>        self.course = course</pre><pre>    }// designated initializer</pre><pre>    convenience init(title: String, author: String) {</pre><pre>    let course = &quot;swift&quot;<br>    self.init(title: title, author: author, course: course)</pre><pre>    }</pre><pre>}</pre><p>Swift provides three rules for delegation between initializers of class type</p><ul><li>Designated initializer must call a <strong>designated initializer</strong> from its immediate super class(it cannot call a convenience initializer)</li><li>A convenience initializer must call an other initializer from same class</li><li>A convenience initializer must ultimately call a designated from same class</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/0*SpOl6RG-rg2izLpg.png" /><figcaption>source- apple docs</figcaption></figure><blockquote>Any initializer (designated or convenience)c an be used to create a fully initialized instance of the class they belong to</blockquote><blockquote>If you find this article useful , give a clap so that medium recommends it to others</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2e8b25d0dab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-ios/initialization-in-swift-part-1-f2e8b25d0dab">Initialization in Swift — Part 1</a> was originally published in <a href="https://medium.com/swift-ios">Swift Programming &amp; iOS Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Networking in swift — Part 1]]></title>
            <link>https://medium.com/swift-ios/networking-in-swift-part-1-c914eae2dff5?source=rss-9db66e72b827------2</link>
            <guid isPermaLink="false">https://medium.com/p/c914eae2dff5</guid>
            <category><![CDATA[url-swift]]></category>
            <category><![CDATA[datatask]]></category>
            <category><![CDATA[urlsessions]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[networking-in-swift]]></category>
            <dc:creator><![CDATA[Shiva Ram Reddy]]></dc:creator>
            <pubDate>Mon, 01 Jul 2019 10:55:22 GMT</pubDate>
            <atom:updated>2019-07-01T10:55:22.900Z</atom:updated>
            <content:encoded><![CDATA[<h3>Networking in swift — Part 1</h3><p>Foundations “URLSession” basics</p><p>Fetching and displaying data on mobile app is very common , to achieve this there are many solutions , in this article we will look at <a href="https://developer.apple.com/documentation/foundation/urlsession">URLSession</a> class and related classes which are part of Foundation framework provided by apple.</p><p><strong><em>URL Creation</em></strong></p><p>Swift’s standard library provides two ways to create url i.e</p><ol><li>URL type :-</li></ol><pre>let url = URL(string: &quot;https://api.github.com/users/kathishivaramreddy&quot;) </pre><pre>//this will give url as optional</pre><p>2. URLComponent :-</p><pre>var components = URLComponents()</pre><pre>components.scheme = &quot;https&quot;</pre><pre>components.host = &quot;api.github.com&quot;</pre><pre>components.path = &quot;/users/kathishivaramreddy&quot;</pre><pre>//this will give url as optional<br>let url = components.url</pre><p>We have successfully constructed url , you can use any of the two ways mentioned above to construct url.We perform network request using URLSession.</p><p><strong>URLSession</strong></p><p>We use <em>URLSession</em> to create a <em>data task and supply a completion closure which is called once data task is completed.</em></p><pre>guard let url = components.url else {<br>    preconditionFailure(&quot;Failed to construct URL&quot;)<br>}</pre><pre>let task = URLSession.shared.dataTask(with: url){ data, response,     <br>                                                               error    <br>        in <br>}</pre><p>URLSession will send three arguments to completion handler once finished</p><ol><li>data :- which is optional contains other download data or nil.</li><li>response :- it contains response information and can be typecasted in HTTPURLResponse if we wish access more http response related information</li><li>error :- error information if encountered otherwise nil.</li></ol><p>For simplicity lets take the information downloaded and convert it into string and print it out for more clarity.As data is optional it needs to be unwrapped .</p><pre>if let data = data {</pre><pre>    print(String(decoding: data, as: UTF8.self))</pre><pre>}else {</pre><pre>   print(String(decoding: error?.localizedDescription, as: UTF8.self))</pre><pre>}</pre><p>Finally to start our data task and perform network request we need to resume it.</p><pre>task.resume()</pre><p>In the part 2 of networking , we will use third party library Alamofire and SwiftyJSON for making network request.</p><p>This article gives you a basic understanding of how to perform network request , but while implementing complete solution there are other tasks involved like posting data , caching and much more .Understanding of this can be easily extended to those.Good Luck</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c914eae2dff5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-ios/networking-in-swift-part-1-c914eae2dff5">Networking in swift — Part 1</a> was originally published in <a href="https://medium.com/swift-ios">Swift Programming &amp; iOS Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optionals in swift]]></title>
            <link>https://medium.com/swift-ios/optionals-in-swift-60685b17969a?source=rss-9db66e72b827------2</link>
            <guid isPermaLink="false">https://medium.com/p/60685b17969a</guid>
            <category><![CDATA[optionals]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Shiva Ram Reddy]]></dc:creator>
            <pubDate>Wed, 15 May 2019 14:00:49 GMT</pubDate>
            <atom:updated>2019-05-15T14:00:49.393Z</atom:updated>
            <content:encoded><![CDATA[<p>What is optional? Internal implementation of optional in swift</p><blockquote><strong><em>Optional</em></strong></blockquote><p>Optional in swift is a type which can hold either a value or no value(nil).If a constant or variable , needs to work with absence of a value , declare it as optional value of appropriate type .</p><p>Optional are declared by adding ? to the type of the variable.Optionals are enum , which make them <em>value types.</em></p><pre>var middleName: String?<br>print(middleName)<br>//prints nil , optional default value, if not assigned is nil</pre><pre>middleName = &quot;Ram&quot;<br>print(middleName)<br>//prints Optional(&quot;Ram&quot;)</pre><blockquote><strong>How are optionals implemented in swift</strong></blockquote><p>Optionals are enumerations, when an optional is declared it looks like this</p><pre>enum Optionals&lt;T&gt; { // A generic type like Array&lt;element&gt;<br>      <br>     case none<br>     case some&lt;T&gt;  // the some case has associated data of type T</pre><pre>}</pre><p>1.What happens when an optional is declared ?</p><pre>var name: String?           ---&gt; var name: Optional&lt;String&gt; = .none</pre><pre>var name: String? = &quot;Shiva&quot; ---&gt; var name: Optional&lt;String&gt; =         .                                                     .some(&quot;Shiva&quot;)</pre><pre>var name: String? = &quot;Shiva&quot; ---&gt; var name: Optional&lt;String&gt; = .none</pre><p>2.How unwrapping is done behind the scenes?</p><p>As enums use switch statement to match value , optionals are unwrapped in the same way</p><p>a.Forced Unwrapping (!)</p><pre>let name: String? = &quot;Shiva&quot;<br>print(name!) </pre><pre>//Implementation</pre><pre>switch name {</pre><pre>       case .none // raise exception<br>       case .some(let data):<br>             print(data)</pre><pre>}</pre><p>b.Optional Binding (if let/var)</p><pre>let name: String? = &quot;Shiva&quot;</pre><pre>if let value = name {<br>     print(value)<br>}else{<br>     print(&quot;No name found&quot;)<br>}</pre><pre>//Implementation</pre><pre>switch name {</pre><pre>       case .none :<br>             print(&quot;No name found&quot;)<br>       case .some(let data):<br>             print(data)</pre><pre>}</pre><p>c.Nil Coalescing (??)</p><pre>let name: String? = &quot;Shiva&quot;<br>let value = name ?? &quot;No Name&quot;</pre><pre>//Implementation</pre><pre>switch name {</pre><pre>       case .none :<br>             value = &quot;No Name&quot;<br>       case .some(let data):<br>             value = data</pre><pre>}<br>Note: A non optional variable or constant cannot contain nil.</pre><blockquote>Conclusion</blockquote><p>Optionals lets you handle condition when a variable or constant can have value or no value ,</p><ol><li>Persons middle name</li><li>A method which can either return a result or nothing (if error occurs)</li><li>It can be used to check whether data has been loaded and then perform appropriate action</li><li>Improves readability</li></ol><p>Thank You !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60685b17969a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-ios/optionals-in-swift-60685b17969a">Optionals in swift</a> was originally published in <a href="https://medium.com/swift-ios">Swift Programming &amp; iOS Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tuple in swift]]></title>
            <link>https://medium.com/swift-ios/tuple-in-swift-ceeaa4d1153e?source=rss-9db66e72b827------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceeaa4d1153e</guid>
            <category><![CDATA[tuples]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Shiva Ram Reddy]]></dc:creator>
            <pubDate>Wed, 15 May 2019 07:31:46 GMT</pubDate>
            <atom:updated>2019-05-15T07:31:46.395Z</atom:updated>
            <content:encoded><![CDATA[<p>What is tuple ? How are tuple useful ?</p><h3><strong>What is a tuple ?</strong></h3><p>It is collection of zero or more types (values) i.e (Int, Double, [Int]).It should not have methods or variables.Tuples are value types.</p><p><strong><em>Usage</em></strong></p><pre>let person: (String, Int, Double) = (&quot;Shiva&quot;, 25, 6.0)<br>//the type of example is &quot;a tuple&quot;</pre><pre>let (name, age, height) = person <br>//this names tuple elements</pre><pre>//accessing tuple values<br>print(name) //prints shiva<br>print(age)  //prints 25<br>print(height) //prints 6.0</pre><pre>//Or tuple values can be named at the declaration also</pre><pre>let person: (name:String, age:Int, height:Double) = (&quot;Shiva&quot;, 25, 6.0)</pre><pre>//accessing tuple values<br>print(person.name) //prints &quot;shiva&quot; </pre><p><em>Accessing tuples through index</em></p><pre>let person = (&quot;Shiva&quot; , &quot;Ram&quot;)</pre><pre>var firstName = person.0<br>var secondName = person.1</pre><p><em>Multiple Assignment in single line using tuple</em></p><pre>var a = 1<br>var b = 2</pre><pre>//This can be done in single line using tuple<br>var (a , b) = (1 , 2)<br>print(a) //prints 1<br>print(b) //prints 2</pre><h3>How are tuple useful ?</h3><p>In swift functions can return only single thing , but that thing can be tuple.Tuple enables function to return multiple values</p><pre>func getDimension() -&gt; (length: Double, breadth: Double) {</pre><pre>return (5,10)</pre><pre>}</pre><pre>let dimension = getDimension()<br>print(dimension.length) //prints 5<br>print(dimension.breadth) //prints 10</pre><p>Thank You !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceeaa4d1153e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-ios/tuple-in-swift-ceeaa4d1153e">Tuple in swift</a> was originally published in <a href="https://medium.com/swift-ios">Swift Programming &amp; iOS Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structs v/s Classes in swift]]></title>
            <link>https://medium.com/swift-ios/structs-v-s-classes-in-swift-bec9cfac737b?source=rss-9db66e72b827------2</link>
            <guid isPermaLink="false">https://medium.com/p/bec9cfac737b</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[class-vs-struct]]></category>
            <category><![CDATA[class-and-struct]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[struct]]></category>
            <dc:creator><![CDATA[Shiva Ram Reddy]]></dc:creator>
            <pubDate>Tue, 14 May 2019 19:13:08 GMT</pubDate>
            <atom:updated>2019-05-15T06:39:00.140Z</atom:updated>
            <content:encoded><![CDATA[<h3>Syntax</h3><p>Class and Struct have similar syntax.Struct definition starts with “struct” keyword whereas Class definition starts with “class” word.</p><pre>class Person {<br>  // class properties and methods<br>}</pre><pre>struct Student {<br>  // struct properties and methods<br>}</pre><p>Whenever class or struct is defined , a new swift type gets defined. As types are declared in UpperCamelCase (Int, String, Double etc) class and struct names should be declared with UpperClassName to differentiate them from properties and methods</p><h3>Difference</h3><p>There are two major difference between class and struct</p><ol><li><em>Inheritance</em> is not possible with struct , whereas class can be inherited.</li><li>Structs are <em>value</em> types , whereas class are <em>reference</em> types.</li></ol><p><strong>Value types v/s Reference types</strong></p><ol><li>A <em>value type</em> is a type whose value is <em>copied</em> when it’s assigned to a variable or constant, or when it’s passed to a function. In fact all the basic types (Int, String, Dictionary , Array) are value types and are implemented as structs.</li><li><em>Reference</em> types are not copied when assigned to a variable or constant , or when passed to function . Instead a reference to same existing instance is used.</li></ol><p><strong><em>Example</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPCHaYp_mdmPfF4ij6ELwA.png" /></figure><p>This example declares a struct called Person which has name and age as its properties and then declares variable firstPerson and sets it to a Person instance initialized with name and age.</p><p>It then declares variable secondPerson and sets it to current value of firstPerson.As Person is a structure a copy is made and assigned to secondPerson.Even though firstPerson and secondPerson have same name and age , both have different instances assigned to them . This is why when you change name of secondPerson , firstPerson is not affected.</p><p>Whereas Student in the example is class , when secondStudent is set to current value of firstStudent , both variable point to same instance.This is why changing the name of secondStudent affects both firstStudent and secondStudent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YB0Egn4EEJSfClU0r9peWQ.jpeg" /></figure><h3>Comparing Classes</h3><p>As classes are reference types, it is possible that multiple variable and constant point to same instance which is not the case with structs.</p><p>Swift provides two identity operators for comparing reference types</p><ul><li>Identical to (===)</li><li>Not identical to (!==)</li></ul><pre>if firstStudent === secondStudent {<br>     print(&quot;first and second student point to same student&quot;)<br>}<br>//Prints first and second student point to same student</pre><h3><strong>Where are reference and value type stored ?</strong></h3><ol><li>Reference Types : are stored in heap and memory management is done by ARC</li><li>Value Types : are stored in stack and memory is destroyed as soon as variable or constant is out of scope.</li></ol><p>Thank You !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bec9cfac737b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-ios/structs-v-s-classes-in-swift-bec9cfac737b">Structs v/s Classes in swift</a> was originally published in <a href="https://medium.com/swift-ios">Swift Programming &amp; iOS Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Property Observers (willSet and didSet) in swift]]></title>
            <link>https://medium.com/swift-ios/property-observers-willset-and-didset-in-swift-94ef35a71342?source=rss-9db66e72b827------2</link>
            <guid isPermaLink="false">https://medium.com/p/94ef35a71342</guid>
            <category><![CDATA[property-observer]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[didset]]></category>
            <category><![CDATA[willset]]></category>
            <dc:creator><![CDATA[Shiva Ram Reddy]]></dc:creator>
            <pubDate>Tue, 14 May 2019 09:33:17 GMT</pubDate>
            <atom:updated>2019-05-14T09:33:17.013Z</atom:updated>
            <content:encoded><![CDATA[<p>Property observers observe(constantly listen to the property value changes on which they are set to) and respond to changes made to properties value , they are called every time property value is set, even if the new value is same as the old value.</p><p>Property Observer are defined using <strong>willSet</strong> or <strong>didSet</strong> or both at the same time</p><ul><li><em>willSet</em> : It is called just before value is set , value being set is passed through parameter , which can be accessed using name newValue .</li><li><em>didSet</em>: It is called just after value is set, old value is passed through parameter, which can be accessed using name oldValue.</li></ul><h3>Example:</h3><p>The example below tracks bank balance , and updates it after each addition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iUhbRuw6CKIumaCZQ1bpdw.png" /></figure><p>In this example whenever property balance is set the property observer will be invoked.</p><p>Initially willSet gets executed , which prints money being added to balance(i.e the newValue which is being set) , it uses custom name “moneyAdded” parameter for newValue</p><p>Then didSet gets invoked , which uses default parameter “oldValue” and prints the total balance.</p><h4>Note:</h4><ol><li>If you pass a property that has observers to a function as an in-out parameter, the willSet and didSet observers are always called.</li><li>Property Observers cannot be defined on <em>lazy store properties.</em></li></ol><p>Thank You !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94ef35a71342" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-ios/property-observers-willset-and-didset-in-swift-94ef35a71342">Property Observers (willSet and didSet) in swift</a> was originally published in <a href="https://medium.com/swift-ios">Swift Programming &amp; iOS Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generics in swift (Basics)]]></title>
            <link>https://medium.com/swift-ios/generics-in-swift-basics-cbf0705f0a69?source=rss-9db66e72b827------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbf0705f0a69</guid>
            <category><![CDATA[generics-in-swift]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-generics]]></category>
            <dc:creator><![CDATA[Shiva Ram Reddy]]></dc:creator>
            <pubDate>Mon, 06 May 2019 13:23:09 GMT</pubDate>
            <atom:updated>2019-05-06T13:23:09.984Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift provides us with generics , which are a very efficient way to handle large number of problems with single type, protocol or function.It enables you to write reusable and flexible code.</p><ul><li><strong>Understanding generics with problem (swapping two values):-</strong></li></ul><p><em>type : Int and String</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bgAILJ3a7QcPuPvJW9sKmQ.png" /></figure><p>Even though both the function are identical ,without generics we need to write separate function for each type.Generic code enables us to write single function which can handle all data types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpLnkhNChG8JLunqj07TAA.png" /><figcaption>swap two values using generics</figcaption></figure><p>To create generics function , we simply have to provide a placeholder(like:-T) and attach constraints if required .It can now be called with any data type . Example:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtpQU3CADSDsaGR6hofQmQ.png" /></figure><ul><li><strong>Generic Types</strong></li></ul><p>In swift we can declare our own generic types, using class, struct , enums etc. Infact swifts fundamental data structure Array , Dictionary are generics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dy8vr34ThCUchcrRMqMYwA.png" /></figure><p>To implement single linkedlist , which can have any value (ex: Int, String or Double), we use generics</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BGCQLDvlJAjM9BVB6c8biA.png" /><figcaption>Node of linkedlist</figcaption></figure><p>This is what makes generics powerful and useful, this articles covers basics of generics which can help you start off with generics.</p><p>Thanks for reading! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbf0705f0a69" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-ios/generics-in-swift-basics-cbf0705f0a69">Generics in swift (Basics)</a> was originally published in <a href="https://medium.com/swift-ios">Swift Programming &amp; iOS Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>