<?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 Pallavi Dipke on Medium]]></title>
        <description><![CDATA[Stories by Pallavi Dipke on Medium]]></description>
        <link>https://medium.com/@pallavidipke07?source=rss-43af1142ebb4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*L_n6paKTVUD5CN6MdYEiPw@2x.jpeg</url>
            <title>Stories by Pallavi Dipke on Medium</title>
            <link>https://medium.com/@pallavidipke07?source=rss-43af1142ebb4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 19:27:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pallavidipke07/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[Method Swizzling in Swift]]></title>
            <link>https://medium.com/@pallavidipke07/method-swizzling-in-swift-5c9d9ab008e4?source=rss-43af1142ebb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c9d9ab008e4</guid>
            <category><![CDATA[method-swizzling]]></category>
            <dc:creator><![CDATA[Pallavi Dipke]]></dc:creator>
            <pubDate>Fri, 14 Jan 2022 19:03:58 GMT</pubDate>
            <atom:updated>2022-01-27T06:12:25.574Z</atom:updated>
            <content:encoded><![CDATA[<p>If you know about method dispatch then method swizzling is not new for you. Even after being big fan of OOP, I didn’t know much about Method Swizzling before. I did digging into for few days and came up with clear picture of Method Swizzling. So let’s explore this topic today without wasting time.</p><figure><img alt="Method Dispatch" src="https://cdn-images-1.medium.com/max/1024/0*BeCz1E8wBRPw7qBu" /></figure><h3>What are use cases of method swizzling?</h3><p>Let’s say you got a task to to keep track of all the screens user is visiting. Its very simple right? Simply create a subclass of <strong>UIViewController</strong> that will hold a function which will perform the tracking logic and we will call that function in <strong>viewWillAppear(_ animated: Bool)</strong> then only thing is left is, use that <strong>UIViewController</strong> class as a base class for all the controllers. But this is not proper solution as, It has following issues.</p><ol><li>You have one <strong>UITableViewController </strong>class and that also need to be logged but when I tried to use our base class as a super class of<strong> UITableViewController it showed following error. </strong>The reason behind this error is <strong>UITableViewController </strong>is child of<strong> UIViewController. Swift doesn’t allow to perform multiple inheritance.</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9byiCCSVz48pdfOtUz8t9g.png" /></figure><p>2. You might be using other frameworks and libraries which may have <strong>UIViewControllers</strong>, also <strong>UITableViewControllers </strong>which<strong> </strong>need to be logged. Now the question here is how you will inherit those <strong>UIViewControllers and UITableViewControllers?</strong></p><p>3. Same point 2 in reverse order. If you are a framework developer and you have to track the screens. You can not ask your users to sub class all the screens with your controller so that tracking of screens will be performed.</p><ul><li>Here, You may write to the library author to use your class as base class so that you can fulfil your requirement with this approach.</li><li>Else, You would have studied about method swizzling and completed the task.</li></ul><p>If you ask me I would have given the task to other teammate and relaxed 😁😁. Joke a part, I would have gone with Method swizzling.</p><h3>What is method swizzling?</h3><blockquote><strong><em>Method swizzling is the process of changing the implementation of an existing selector at runtime. Simply speaking, we can change the functionality of a method at runtime.This is possible with the power of objective C runtime.</em></strong></blockquote><p>Now first question pop up in my mind that what exactly happens at the memory level when method swizzling (<strong>Message Dispatch</strong>) happens. Here what happens -</p><ul><li>In case of message dispatch compiler does not have any direct dispatch mechanism nor witness table to look into to execute the function. Actually compiler crawl to the hierarchy of classes to determine which method to invoke. This is comparatively very slow compared to direct and table dispatch but still there are some use cases where is no option out there.</li></ul><h3>How to achieve it?</h3><p>Following code will creates an extension of UIViewController. Let’s understand the code now.</p><ul><li>swizzle() function holds a logic for swizzling. Here it will get the references of the methods which we want to exchange at runtime.</li><li>create a function which we want to execute at runtime when the message dispatches for particular method. In example. We have created <strong>_tracked_viewWillAppear(_ animated: Bool). </strong>Here we can write the logic of tracking the screens which is our problem statement.</li><li><strong>class_getInstanceMethod(_ cls: AnyClass?, _ name: Selector) -&gt; Method? </strong>This objective C function which will return the pointers for the function. It takes two parameters, one is type of AnyClass, We will set self here and method selector is second parameter which will be <strong>#selector.</strong></li><li>Here we have to get pointers of two methods and store it in a local variable. In example we have to get pointers of <strong>_tracked_viewWillAppear(_:)</strong> and <strong>viewDidLoad.</strong></li><li>Then the last step for this function is exchange the implementation by using <strong>method_exchangeImplementations(_ m1: Method, _ m2: Method) </strong>function.</li><li>To execute this throughout the app just call the method from AppDelegate. Tired 😟?? Relax now, you are all done with the coding for the given problem statement.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LIPDu6yDCF6H4QSs_a-cWg.png" /><figcaption>Swizzling Method implementation.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NqW5nOF3w6PQm4FDIWAueA.png" /><figcaption>Calling Swizzling function for all ViewControllers.</figcaption></figure><ul><li>You might wonder we are calling <strong>_tracked_viewWillAppear(animated) </strong>inside<strong> _tracked_viewWillAppear(_:). </strong>This may call the same function infinite times and it will never come out of loop. But it’s not like that. In fact it will call the<strong> viewDidLoad()</strong> with <strong>_tracked_viewWillAppear(_:) </strong>call.</li></ul><p>Here is output of this code:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMyVVWc7Fay_GSgnh-_fig.png" /><figcaption>Outcome of the code.</figcaption></figure><h3>Things to be careful for</h3><ul><li>Method swizzling is very dynamic in nature as takes decision at runtime, hence we have to be very careful while using it as it has ability to mess up the app if you are not using it properly.</li><li>Trouble shooting can be very difficult if something goes wrong.</li><li>The order of swizzle matters, so be careful when swizzling multiples classes. For example if you swizzle <strong>UIView</strong> and <strong>UIButton</strong> you must be careful because <strong>UIButton</strong> inherits from <strong>UIView </strong>through UIControls.</li><li>You have to keep track of iOS releases and have to check that your code is running properly with the updates. Even Firebase does swizzling for few methods but it allows us to disable the it.</li><li>Uses subclassing wherever possible until its necessary to go with swizzling.</li></ul><p>This is all for now on this topic, Hope it improved your understanding about Method swizzling.</p><p>Articles that inspired me to learn about swizzling.</p><ul><li><a href="https://pspdfkit.com/blog/2019/swizzling-in-swift/">Swizzling in Swift | PSPDFKit</a></li><li><a href="https://medium.com/rocknnull/ios-to-swizzle-or-not-to-swizzle-f8b0ed4a1ce6">iOS — To swizzle or not to swizzle?</a></li><li><a href="https://trinhngocthuyen.github.io/posts/tech/method-dispatch-in-swift/">Method dispatch in Swift</a></li></ul><blockquote><em>If you find this article useful , give a clap so that medium recommends it to others.</em></blockquote><p>Swift iOS Method Dispatch iOS Development Method Swizzling Monkey Patching</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c9d9ab008e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Method Dispatch in Swift]]></title>
            <link>https://medium.com/@pallavidipke07/method-dispatch-in-swift-b113a40a713a?source=rss-43af1142ebb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b113a40a713a</guid>
            <dc:creator><![CDATA[Pallavi Dipke]]></dc:creator>
            <pubDate>Wed, 05 Jan 2022 14:17:07 GMT</pubDate>
            <atom:updated>2022-03-28T12:29:58.329Z</atom:updated>
            <content:encoded><![CDATA[<p>Many of you must have faced this question in interviews or also have wondered how function call is been managed in Swift. Well, let’s deep dive into this.</p><p>As a developer we should be very particular about what kind of function we should write which will be faster enough in terms of execution. We should not rely and say that swift is anyways faster than obj-c then what else we should do? Well, here our topic pops up.</p><blockquote><em>As definition says,</em> Method Dispatch is how a program selects which instructions to execute when invoking a method. It’s something that happens every time a method is called, and not something that you tend to think a lot about.</blockquote><p>Compiled programming languages have <strong>three</strong> primary methods of dispatch.</p><p><strong><em>1.Static or direct dispatch</em></strong></p><p><strong><em>2.Table or dynamic dispatch</em></strong></p><p><strong><em>3.Message dispatch</em></strong></p><h3>Direct Dispatch</h3><p>Direct dispatch is the fastest style of method dispatch. Not only does it result in the fewest number of assembly instructions, but the compiler can perform all sorts of smart tricks, like inlining code, and many more things which are outside of the scope of this article. This is often referred to as static dispatch.</p><p>However, direct dispatch is also the most restrictive from a programming point of view, and it is not dynamic enough to support subclassing.</p><blockquote><strong>Structs (Value type Data type)</strong></blockquote><blockquote><strong>Static and final (Reference type with this keyword)</strong></blockquote><h3>Table Dispatch <strong><em>or Dynamic dispatch</em></strong></h3><p>Table dispatch is the most common implementation of dynamic behaviour in compiled languages. Table dispatch uses an <strong>array</strong> of function pointers for each method in the class declaration. Most languages refer to this as a <strong>“virtual table,”</strong> but Swift uses the term <strong>“witness table.</strong>” Every subclass has its own copy of the table with a different function pointer for every method that the class has overridden.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*s7UpvOYIOMh18WXZDzosvQ.png" /></figure><p>This code will create array for function address, As subclasses add new methods to the class, those methods are appended to the end of this array. This table is then consulted at runtime to determine the method to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4YaI2HPK48IqgyK3DpU_VQ.png" /><figcaption>Array for function pointers.</figcaption></figure><p>However, this method of dispatch is still slow compared to direct dispatch. From a byte-code point of view, there are two additional reads and a jump, which contribute some overhead. However, another reason this is considered slow is that the compiler can’t perform any optimisations based on what is occurring inside the method.</p><p>One downfall of this array-based implementation is that extensions cannot extend the dispatch table. Since subclasses add new methods to the end of the dispatch table, there’s no index that an extension can safely add a function pointer to.</p><h3>Message Dispatch</h3><p>Though this Message dispatch technique is the most dynamic type, this is slowest of all other dispatch types<strong>. In Table Dispatch the witness table is getting generated on compile time</strong> but in message dispatch this not possible to decide which method to be called since it might have been swizzled or new methods might have been added during runtime. However Cocoa frameworks use it inside a lot of its big players like KVO, Core Data, and other things.</p><p>Also, it enables <em>method swizzling</em>, which generally means that using this technique, we can change the functionality of a method at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*epLHLRxlL7Sgi0xQ3g_wgQ.png" /><figcaption>Structure of method pointer array</figcaption></figure><p>When a message is dispatched, the runtime will crawl the class hierarchy to determine which method to invoke. This is not really very slow as it has been implemented with high performance cache.</p><blockquote><em>The compiler always try to upgrade the dispatch technique to static dispatch unless we have explicitly marked it with </em>dynamic, @objc<em> keyword</em></blockquote><p>let’s understand this by following code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSKQMbXDBqj1Lwrv9279xA.png" /></figure><p>In code we can see error saying the function can not be overridden in extension. This is because sayHi() is declared in an extension meaning that the method will be invoked with message dispatch. When hello(person:) is invoked, sayHi()is dispatched to the ParentClass object via table dispatch. Since the ClildClass override was added via message dispatch, the dispatch table for ClildClass still has the ParentClass implementation in the dispatch table hence confusion happens and you will get error. To make this work we can either move this extension method to ClildClass and not in extension ClildClass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NRp-XlFE4_jF7f4wpLJb_Q.png" /><figcaption>Method dispatch based on type of data structure.</figcaption></figure><p>There are a few things to note here:</p><ul><li>Value types always use direct dispatch. Nice and easy!</li><li>Extensions of protocols and classes use direct dispatch.</li><li>NSObject extensions use message dispatch</li><li>NSObject uses table dispatch for methods inside the initial declaration!</li><li>Default implementations of methods in the initial protocol declaration use table dispatch.</li></ul><p>Hope this has solved your doubts with method dispatch. Any improvement or any other queries always appreciated.</p><p><strong>References:-</strong></p><p>Below are few articles which inspired me to pickup this topic.</p><ul><li><a href="https://www.rightpoint.com/rplabs/switch-method-dispatch-table">Method Dispatch in Swift</a></li><li><a href="https://medium.com/@venki0119/method-dispatch-in-swift-effects-of-it-on-performance-b5f120e497d3">Method Dispatch in Swift, and its effect on performance</a></li></ul><p>Swift iOS Method Dispatch iOS Development</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b113a40a713a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy Computed Properties In Swift]]></title>
            <link>https://medium.com/@pallavidipke07/lazy-computed-properties-in-swift-4b840933bd1e?source=rss-43af1142ebb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b840933bd1e</guid>
            <dc:creator><![CDATA[Pallavi Dipke]]></dc:creator>
            <pubDate>Sat, 04 Apr 2020 13:33:54 GMT</pubDate>
            <atom:updated>2020-04-04T13:33:54.690Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Lazy computed properties</em> make your code more efficient and easier to read. Let’s see how in coming few minutes…</h4><p><em>Lazy</em> is something which comes to stage only when we need to perform task using those properties. this is real life scenario but it has no difference in our programming world.</p><p><strong><em>Apple Says: —</em></strong></p><blockquote>A Lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored properties by writing the lazy modifier before its declaration.</blockquote><h3>How To Use Lazy Initialization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*DuGOSOZ_Znhy1ahyiyx9iQ.png" /><figcaption>income and age gets initialized with default values.</figcaption></figure><p>here,we don’t really want to initialize age and income with object creation only.so here is <em>lazy initialization</em> comes in picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*Fb4SPiD5VkdE6kYFoXgmPg.png" /><figcaption>income and age dont initialized with default values.</figcaption></figure><p>Lazy initialization (also sometimes called lazy instantiation, or lazy loading) is a technique for delaying the creation of an object or some other expensive process until it’s needed. When programming for iOS, this is helpful to make sure you utilize only the memory you need when you need it.</p><p>This technique is so helpful, in fact, that Swift added direct support for it with the lazy attribute.</p><p><strong>Lazy initialization is helpful in two scenarios:</strong></p><ul><li>When the value of the property is dependent on factors unknown at initialization of the object</li><li>When the initial value of the property requires complex computations or is intensive to calculate</li></ul><p>In both scenarios it doesn’t make sense to initialize the property when the object is initialized, so that’s when you use lazy initialization.</p><h3><strong>What is Computed Properties?</strong></h3><p>Classes, structures, and enumerations can define <em>computed properties</em>, which do not actually store a value. Instead, they returns values (i.e have getter and optional setter).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*6Wd-6jqy1PneLiDA3gFlHA.png" /><figcaption>class has volume as computed property.</figcaption></figure><h3>Lazy Computed Properties.</h3><p>Ok Now you will say it’s ok to initialise computed properties as lazy but where to use it?</p><ul><li>When it doesn’t make sense to set an initial value when initializing the object, for instance because it depends on unknown outside factors.</li><li>When a computed property is computationally intensive, for instance when it calculates something complex.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*ZXpT4ufo5P-VE0UNun0eeA.png" /><figcaption>lazily initialized computed property.</figcaption></figure><p><strong><em>so you will say,it looks like function or closure because they are also get initialized when they calls and return value too,Right?</em></strong></p><blockquote>Sometimes it’s just more elegant to define a property as a<em> lazy computed property</em>, instead of writing it as a function. After all, you can code a function in such a way that it’ll only recalculate a returned value if it hadn’t done so before — right?</blockquote><p>Keywords like lazy, and closures, can add to the readability and maintainability of your code. With lazy computed properties you can keep your code more cleaner to understand by new members to our team and flexibility to use those in future.</p><p>Easy Right?Hopethis blog could help you to understand the lazy properties in a ease.Any suggestions will be always be pleased.</p><p>You can catch me at:</p><p><strong>LinkedIn: </strong><a href="https://in.linkedin.com/in/pallavi-dipke-88882b125?challengeId=AQEazhbKjZvr5QAAAXEYII01mZpEUiS1Ju39hPWW0Snaz8v_mDoYJVTDfzrsivAG4-ayUvMjaY-nou4klwRY5pZ3DBHJZUPsew&amp;submissionId=95fa0b9b-66ee-ff15-ba94-3e209074a335"><strong>Pallavi Dipke</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b840933bd1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[for loop in swift with stride() — to loop over a range.]]></title>
            <link>https://medium.com/@pallavidipke07/for-loop-in-swift-with-stride-to-loop-over-a-range-ee0c6db66797?source=rss-43af1142ebb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee0c6db66797</guid>
            <category><![CDATA[stride]]></category>
            <category><![CDATA[for-loop-with-stride]]></category>
            <dc:creator><![CDATA[Pallavi Dipke]]></dc:creator>
            <pubDate>Thu, 26 Mar 2020 18:42:17 GMT</pubDate>
            <atom:updated>2020-03-26T18:42:17.721Z</atom:updated>
            <content:encoded><![CDATA[<h3>for loop in swift with stride() — to loop over a range.</h3><p>Most of us usefor loop like below..</p><pre>for i in 0...10 { <br>// for both 0 and 10 included.<br>print(i)<br>// prints 0 to 10<br>}</pre><pre><br>for i in 0..&lt;10 { <br>// for 0 to 9 .<br>print(i) <br>// prints 0 to 9}</pre><pre> }</pre><p>this is fair enough if your range is incrementing by 1.what if you want to increment the range accoring to your need. Never thought right?? No worries me too never fall in the situation like this before.</p><p>We all are familiar with the classic for loop in c language. Just have a look at the code below.</p><pre>for (int i = 0; i &lt; 10; i += 1){<br>    print(i) <br>// prints from 0 to 9<br>}</pre><p><em>The c- style for loops are no longer supported in swift. The </em><em>for loop that we have in swift today will not allow us to do the functionality explained above.</em></p><p><strong><em>So the solution for this case in swift is stride(). how to use this lets see…</em></strong></p><p><em>what apple says stride() is:</em></p><blockquote><strong><em>Strideable</em></strong><em>: Conforming types are notionally continuous, one-dimensional values that can be offset and measured.</em></blockquote><p>Not getting?? Ok,I will explain.</p><blockquote><strong><em>Stride()</em></strong> is a <a href="https://medium.com/swift-india/power-of-swift-generics-part-1-ab722a030dc2"><strong><em>generic function</em></strong></a> confirming <strong><em>Stridable protocol,</em></strong>which lets you move from one value to another using any increment and even lets you specify whether the upper bound is exclusive or inclusive.</blockquote><h4>Declaration for stride(from:to:by:) — <a href="https://developer.apple.com/reference/swift/1641347-stride#declarations">apple docs</a></h4><p>Returns a sequence from a starting value to, but not including, an end value, stepping by the specified amount.</p><pre>func stride&lt;T&gt;(from start: T, to end: T, by stride: T.Stride) -&gt; StrideTo&lt;T&gt; where T : Strideable</pre><h4>Declaration for stride(from:through:by:) — <a href="https://developer.apple.com/reference/swift/1641185-stride">apple docs</a></h4><p>Returns a sequence from a starting value toward, and possibly including, an end value, stepping by the specified amount.</p><pre>func stride&lt;T&gt;(from start: T, through end: T, by stride: T.Stride) -&gt; StrideThrough&lt;T&gt; where T : Strideable</pre><h3>Swift has two types of stride functions:</h3><h4>‣ stride(from:to:by:)</h4><p>stride(from:to:by:) counts from the start point up to by <strong><em>excluding</em></strong> the <strong><em>to</em></strong>parameter. So, the above for-loop can be written in swift using stride as:</p><pre>for i in stride(from: 0, to: 10, by: 2) {<br>    print(i) // prints 0,2,4,6,8<br>}</pre><h4>‣ stride(from:through:by:)</h4><p>stride(from:through:by:) counts from the start point up to by <strong><em>including</em></strong> the <strong><em>through</em></strong> parameter.</p><pre>for i in stride(from: 0, through: 10, by: 2) {<br>    print(i) // prints 0,2,4,6,8,10<br>}</pre><h4>Benefits of using Stride()</h4><p>1.stride works with non-integer values.See the code below.</p><pre>for r in stride(from: 3.14, to: 234.14234, by: 5.6345) {<br>}</pre><p>2.stride has the by parameter to increment value of iteration according to your need.</p><p>Hope I could help you.Thanks for reading article.</p><p>You can catch me at:</p><p><strong>LinkedIn: </strong><a href="https://in.linkedin.com/in/pallavi-dipke-88882b125?challengeId=AQEazhbKjZvr5QAAAXEYII01mZpEUiS1Ju39hPWW0Snaz8v_mDoYJVTDfzrsivAG4-ayUvMjaY-nou4klwRY5pZ3DBHJZUPsew&amp;submissionId=95fa0b9b-66ee-ff15-ba94-3e209074a335"><strong>Pallavi Dipke</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee0c6db66797" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>