<?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 Ravi Ranjan on Medium]]></title>
        <description><![CDATA[Stories by Ravi Ranjan on Medium]]></description>
        <link>https://medium.com/@r.ranjanchn?source=rss-4a4cf29301a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*P_dNUD_Y7lQDUQlau3sH_w@2x.jpeg</url>
            <title>Stories by Ravi Ranjan on Medium</title>
            <link>https://medium.com/@r.ranjanchn?source=rss-4a4cf29301a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 02:29:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@r.ranjanchn/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[iOS Interview: Factory Design Pattern]]></title>
            <link>https://medium.com/codex/ios-interview-factory-design-pattern-793e4b6d4a9c?source=rss-4a4cf29301a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/793e4b6d4a9c</guid>
            <category><![CDATA[factory-farming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Ravi Ranjan]]></dc:creator>
            <pubDate>Sun, 15 Jan 2023 19:34:23 GMT</pubDate>
            <atom:updated>2023-01-18T13:25:41.835Z</atom:updated>
            <content:encoded><![CDATA[<p>The Factory Design Pattern is a creational design pattern that provides a way to create objects without specifying the exact class of object that will be created. In Swift, the factory pattern can be implemented by creating a factory class that has a method for creating objects of a specific type. This method can either be a static method or an instance method, depending on the needs of the application.</p><p>One common implementation of the factory pattern in Swift is to use an enumeration to define the different types of objects that can be created. The factory class will have a method that takes in a case of this enumeration and returns an object of the corresponding type.</p><p>For example, let’s say we have an app that needs to create different types of vehicles, such as cars, trucks, and motorcycles. We can create an enumeration called “VehicleType” with cases for each type of vehicle. Then, we can create a factory class called “VehicleFactory” that has a method called “createVehicle” that takes in a “VehicleType” case and returns an object of the corresponding type</p><pre>enum VehicleType {<br>    case car<br>    case truck<br>    case motorcycle<br>}<br><br>class VehicleFactory {<br>    static func createVehicle(type: VehicleType) -&gt; Vehicle {<br>        switch type {<br>            case .car:<br>                return Car()<br>            case .truck:<br>                return Truck()<br>            case .motorcycle:<br>                return Motorcycle()<br>        }<br>    }<br>}</pre><p>In this example, the createVehicle method uses a switch statement to determine the type of vehicle to create based on the input case. It then returns a new instance of the corresponding class (Car, Truck, or Motorcycle).</p><p>By using the factory pattern, we have separated the process of creating objects from the classes that use them. This allows for more flexibility in the future, as new types of vehicles can be added without affecting the existing code.</p><p>Another way to implement the factory pattern in Swift is by using a protocol and extensions. This approach involves creating a protocol that defines the methods and properties that the objects created by the factory must conform to. Then, we can create extensions for this protocol for each specific type of object that we want to create.</p><p>For example, let’s say we have a protocol called “Shape” that defines methods for calculating the area and perimeter of a shape. We can create extensions for this protocol for different types of shapes, such as circles, squares, and rectangles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6tgZHi3QbH_ciav9idPWA.png" /></figure><pre>enum ShapeType {<br>    case circle<br>    case square<br>    case rectangle<br>}<br><br>protocol Shape {<br>    func area() -&gt; Double<br>    func perimeter() -&gt; Double<br>}<br><br>extension Shape {<br>    func create(type: ShapeType) -&gt; Shape {<br>        switch type {<br>        case .circle:<br>            return Circle()<br>        case .square:<br>            return Square()<br>        case .rectangle:<br>            return Rectangle()<br>        }<br>    }<br>}</pre><p>In this example, the create method takes in a Shapetype Enum that represents the type of shape to create and returns an object that conforms to the Shape protocol. By using the protocol and extensions approach, we can use the factory pattern to create objects of different types, while still ensuring that they conform to a set of common methods and properties.</p><p>In conclusion, The Factory pattern is a great way to create objects in a decoupled and flexible way, giving you the ability to change the creation process without affecting the rest of the codebase.</p><p><strong><em>I have created a video for factory design pattern for the Textfield validator for every input type, the video link is in the comment box. If you liked this, click the 💚 and give a clap on this post as much as you can below so other people will see this here on Medium. If you have any queries or suggestions, feel free to comment or hit me on </em></strong><a href="https://twitter.com/b_banzara"><strong><em>Twitter</em></strong></a><strong><em>, or </em></strong><a href="https://www.linkedin.com/in/rranjanchchn/"><strong><em>Linkedin</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=793e4b6d4a9c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/ios-interview-factory-design-pattern-793e4b6d4a9c">iOS Interview: Factory Design Pattern</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 10 mistakes swift developers do]]></title>
            <link>https://medium.com/codex/top-10-mistakes-swift-developers-do-1c20e81f93c5?source=rss-4a4cf29301a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c20e81f93c5</guid>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ravi Ranjan]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 19:49:40 GMT</pubDate>
            <atom:updated>2023-01-17T20:13:49.572Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s blog, we will discuss the top 10 mistakes we do as iOS developers, if you are just starting iOS development then keep these points so that you will write more flexible, maintainable, less verbose, and less error-prone code.</p><blockquote><strong>Mistake number 1:</strong> Not properly handling optionals. Optionals are a powerful tool in Swift, but failing to properly handle them can lead to runtime crashes. Make sure to always check for nil values before unwrapping optionals.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*oRRV-aaMkVnSqkHO0wBjCw.png" /><figcaption>Optional</figcaption></figure><blockquote><strong>Mistake number 2:</strong> Not properly handling errors. Swift uses the do-try-catch syntax to handle errors thrown by functions. Neglecting to catch and handle errors can result in unexpected behavior or crashes.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bh78wINiZMw8yx3mDVwSwg.jpeg" /></figure><blockquote><strong>Mistake number 3</strong>: Not using guard statements. Guard statements help ensure that certain conditions are met before executing a block of code. Failing to use guard statements can make your code harder to read and debug.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*2RnMs9DTZSpDGlHCvUruNg.png" /></figure><blockquote><strong>Mistake number 4:</strong> Not using type inference. Swift has powerful type inference capabilities, which allow the compiler to infer the type of a variable based on its value. Neglecting to use of type inference can make your code more verbose and less readable.</blockquote><blockquote><strong>Mistake number 5:</strong> Not using option sets. Option sets are a powerful tool for representing groups of options in a concise and expressive way. Failing to use option sets can result in code that is more verbose and less readable.</blockquote><blockquote><strong>Mistake number 6:</strong> Not using enums effectively. Enums are a powerful tool for representing a finite set of values in a concise and expressive way. Neglecting to use of enums effectively can result in code that is more verbose and less readable.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*AHIafV4gor-etxSYwGer3g.png" /></figure><blockquote><strong>Mistake number 7:</strong> Not using protocols effectively. Protocols are a powerful tool for defining contracts in Swift. Failing to use protocols effectively can result in code that is less flexible and more difficult to maintain.</blockquote><blockquote><strong>Mistake number 8:</strong> Not using associated types in protocols. Associated types are a powerful feature of protocols that allow you to define a placeholder type that is used in the protocol definition. Failing to use associated types can result in code that is less flexible and more difficult to maintain.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ELEAz-FZ1I_XgsRKlHB54A.jpeg" /></figure><blockquote><strong>Mistake number 9: </strong>Not using higher-order functions. Higher-order functions are functions that take other functions as arguments or return them as results. Failing to use higher-order functions can result in code that is less concise and expressive.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xkT3Y_oeyM9EjZ30mc6PxQ.png" /></figure><blockquote><strong>Mistake number 10:</strong> Not using the right data structures. Swift provides a variety of data structures, such as arrays, sets, and dictionaries, each of which has specific strengths and use cases. Failing to choose the right data structure can result in code that is less efficient or less expressive.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2CmR6i1xvoqKCw0zPMUKIw.png" /></figure><p>Above are the mistakes we do as junior developers and also as senior developers. feel free to add more points if you think they needed to be added.</p><p><strong><em>If you liked this, click the 💚 and give a clap on this post as much as you can below so other people will see this here on Medium. Also Please share this with your friends, and colleagues also on Linkedin and Twitter. If you have any queries or suggestions, feel free to comment or hit me on </em></strong><a href="https://twitter.com/b_banzara"><strong><em>Twitter</em></strong></a><strong><em>, or </em></strong><a href="https://www.linkedin.com/in/rranjanchchn/"><strong><em>Linkedin</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c20e81f93c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/top-10-mistakes-swift-developers-do-1c20e81f93c5">Top 10 mistakes swift developers do</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Interview: Struct vs Class [Performance metrics- which one is faster]]]></title>
            <link>https://medium.com/codex/ios-interview-struct-vs-class-performance-metrics-which-one-is-faster-574bf3c8d9d4?source=rss-4a4cf29301a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/574bf3c8d9d4</guid>
            <category><![CDATA[application-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[class-vs-struct]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Ravi Ranjan]]></dc:creator>
            <pubDate>Sun, 25 Dec 2022 08:27:52 GMT</pubDate>
            <atom:updated>2022-12-25T11:13:17.123Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Often we see a debate or generally an iOS interview question asking the difference between struct and Classes and when we should use struct and when should we use class.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*IBgaMzasPErohwuC0bgM8g.jpeg" /></figure><h3><strong>Fundamentals:</strong></h3><blockquote>In Swift, a class is a reference type, while a struct is a value type. This means that when you pass an instance of a class to a function or assign it to a constant or variable, you are passing a reference to the object, rather than the object itself. On the other hand, when you pass an instance of a struct to a function or assign it to a constant or variable, you are passing a copy of the object.</blockquote><h3>Here are some key differences between classes and structs in Swift:</h3><blockquote>1. Inheritance: Classes can inherit from other classes, while structs cannot. This means that a class can be a subclass of another class and can inherit properties and methods from its superclass. Structs, on the other hand, cannot have a superclass and cannot be subclassed.</blockquote><blockquote>2. Memory management: Classes use reference counting for memory management, while structs do not. This means that when you create an instance of a class, it is stored in the heap and a reference to it is stored in the stack. When there are no more references to the object, it is deallocated from the heap. Structs, on the other hand, are stored and passed by value, so they are always copied when they are assigned to a constant or variable or passed to a function.</blockquote><blockquote>3. Mutability: Classes can be mutable or immutable, while structs are always mutable. This means that you can change the properties of a class instance after it has been created, while the properties of a struct cannot be changed once it has been created.</blockquote><h3><strong>When to use Class and when to use struct?</strong></h3><p>In swift we have two types of objects one is a value type and another one is a reference type. as discussed above classes are of reference type and structs are of value type other than that we have enums as well which are of the value type.</p><p>Application performance also depends on the usage of value type and reference type objects as when we create a class or struct and write any method then the code gets compiled and methods are tracked with a witness table so that we access those method compilers directly go to the witness table and execute the method. this process is called Dispatch [it is different for dispatch queue]. there are three types of dispatch:</p><p>1- Static Dispatch (it is also called Direct dispatch)</p><p>2- Dynamic Dispatch (it is also called Table Dispatch)</p><p>3- Message Dispatch</p><p>So whenever you call a function from a struct compiler directly goes to that method because a <strong>struct</strong> is a value type and the compiler knows there we only one value of that instance this dispatch is called <strong>Static Dispatch</strong> and this is the fastest one.</p><p>but when a function is called from a reference type of instance the compiler makes an array of function pointers (witness table ). And when a function is invoked, its address is searched in the witness table at runtime and then the invocation happens. this is because we can perform inheritance in reference type the compiler takes some time to execute the exact method by finding its references from the witness table.</p><p>So we can conclude that struct is faster and more efficient than classes however we can make our classes use static dispatch by tweaking some keywords like Final, and private.</p><h3>Here are some additional considerations to keep in mind when choosing between a class and a struct:</h3><blockquote>Performance: Structs are generally faster and use less memory than classes because they are stored and passed by value rather than by reference. This can be important if you are working with large data structures or if you need to optimize the performance of your app.</blockquote><blockquote>Mutability: Structs are always mutable, while classes can be either mutable or immutable. If you need an immutable object, you should use a class and mark its properties as let.</blockquote><blockquote>Copy-on-write: Structs use copy-on-write optimization, which means that they are only copied when they are modified. This can be useful if you have a large data structure that you want to pass around, but you don’t want to pay the cost of copying it unless you need to modify it.</blockquote><blockquote>Reference cycles: Classes can create reference cycles, which can lead to memory leaks if they are not properly managed. Structs do not have this problem because they are always copied when they are passed around.</blockquote><p><strong><em>If you liked this, click the 💚 and give a clap on this post as much as you can below so other people will see this here on Medium. Also Please share this with your friends, and colleagues also on Linkedin and Twitter. If you have any queries or suggestions, feel free to comment or hit me on </em></strong><a href="https://twitter.com/b_banzara"><strong><em>Twitter</em></strong></a><strong><em>, or </em></strong><a href="https://www.linkedin.com/in/rranjanchchn/"><strong><em>Linkedin</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=574bf3c8d9d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/ios-interview-struct-vs-class-performance-metrics-which-one-is-faster-574bf3c8d9d4">iOS Interview: Struct vs Class [Performance metrics- which one is faster]</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Interview: Dependency Injection [Types and implementation]]]></title>
            <link>https://medium.com/codex/ios-interview-dependency-injection-types-and-implementation-a216d182f047?source=rss-4a4cf29301a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a216d182f047</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Ravi Ranjan]]></dc:creator>
            <pubDate>Tue, 20 Dec 2022 19:11:41 GMT</pubDate>
            <atom:updated>2022-12-21T01:17:42.539Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever faced these below questions when you start giving an interview for an iOS developer job?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SyFZzBUYDlvXfI0oSZbJvA.jpeg" /><figcaption>DI</figcaption></figure><blockquote>1. What is dependency injection?</blockquote><blockquote>2. What are the benefits of dependency injection?</blockquote><blockquote>3. what are the types of dependency injection?</blockquote><p>And surprisingly you have used dependency injection somewhere in your code but you are unable to explain it with the concept.</p><p>So let’s start understanding dependency injection.</p><p><strong>Dependency Injection is a software design pattern in which an object receives other instances that it depends on.</strong></p><p>So the question comes is if everything was working fine by creating an object of the class and then using the property and function why do we need dependency injection? And the reason behind it is that dependency injection gives the power to write more testable, reusable code which helps us to write maintainable software where we can perform the test with mocked data and it will simplify testing. it is a design pattern that involves providing a component with its dependencies rather than having the component itself create or locate them. This can be useful for a number of reasons, including:</p><ul><li><em>It makes it easier to test components in isolation, as you can inject mock dependencies rather than having to set up the real ones.</em></li><li><em>It allows you to decouple components from each other, making it easier to reuse and maintain them.</em></li><li><em>It can make it easier to manage complex systems, as you can define the dependencies at a central location rather than having them scattered throughout the codebase.</em></li></ul><p>There are several ways to implement dependency injection in Swift, depending on the needs of your application. Some common approaches include:<br><strong>1. Constructor injection</strong>: This involves passing the dependencies as parameters to the component’s initializer. below is the example for Constructor injection.</p><pre>class NetworkClient {<br>  func performRequest(url: URL) {<br>    // Perform network request<br>  }<br>}<br><br>class UserService {<br>  let networkClient: NetworkClient<br><br>  init(networkClient: NetworkClient) {<br>    self.networkClient = networkClient<br>  }<br><br>  func fetchUsers() {<br>    let url = URL(string: &quot;url&quot;)!<br>    networkClient.performRequest(url: url)<br>  }<br>}<br><br>let networkClient = NetworkClient()<br>let userService = UserService(networkClient: networkClient)<br>userService.fetchUsers()</pre><p>In the above example, the UserService depends on a NetworkClient to perform network requests. The NetworkClient is injected into the UserService via the initialiser, and the UserService can then use the NetworkClient to perform the request.</p><p><strong>2. Property injection:</strong> This involves setting the dependencies on the component as properties after it has been initialized.</p><pre>class UserService {<br>  var networkClient: NetworkClient?<br><br>  func fetchUsers() {<br>    let url = URL(string: &quot;url&quot;)!<br>    networkClient?.performRequest(url: url)<br>  }<br>}<br><br>let networkClient = NetworkClient()<br>let userService = UserService()<br>userService.networkClient = networkClient<br>userService.fetchUsers()</pre><p><strong>3. Method injection:</strong> This involves passing the dependencies as arguments to the method that needs them.</p><pre>class UserService {<br>  func fetchUsers(using networkClient: NetworkClient) {<br>    let url = URL(string: &quot;url&quot;)!<br>    networkClient.performRequest(url: url)<br>  }<br>}<br><br>let networkClient = NetworkClient()<br>let userService = UserService()<br>userService.fetchUsers(using: networkClient)</pre><p><strong>4. Interface injection:</strong> This involves defining an interface for the dependencies, and having the component implement that interface. This can be useful when the component needs to use multiple dependencies that have a similar roles, but different implementations. For example:</p><pre>protocol NetworkClient {<br>  func performRequest(url: URL)<br>}<br><br>class HTTPNetworkClient: NetworkClient {<br>  func performRequest(url: URL) {<br>    // Perform network request using HTTP<br>  }<br>}<br><br>class UserService {<br>  var networkClient: NetworkClient<br><br>  init(networkClient: NetworkClient) {<br>    self.networkClient = networkClient<br>  }<br><br>  func fetchUsers() {<br>    let url = URL(string: &quot;url&quot;)!<br>    networkClient.performRequest(url: url)<br>  }<br>}<br><br>let networkClient = HTTPNetworkClient()<br>let userService = UserService(networkClient: networkClient)<br>userService.fetchUsers()</pre><p><strong><em>If you liked this, click the 💚 and give a clap on this post as much as you can below so other people will see this here on Medium. If you have any queries or suggestions, feel free to comment or hit me on </em></strong><a href="https://twitter.com/b_banzara"><strong><em>Twitter</em></strong></a><strong><em>, or </em></strong><a href="https://www.linkedin.com/in/rranjanchchn/"><strong><em>Linkedin</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a216d182f047" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/ios-interview-dependency-injection-types-and-implementation-a216d182f047">iOS Interview: Dependency Injection [Types and implementation]</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Interview: Background Fetch || Background Task]]></title>
            <link>https://medium.com/codex/ios-interview-background-fetch-background-task-5ed92eb11997?source=rss-4a4cf29301a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ed92eb11997</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[background-task]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Ravi Ranjan]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 19:40:34 GMT</pubDate>
            <atom:updated>2022-12-20T11:00:00.629Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A</strong> background task in iOS is a piece of code that is executed while an app is in the background (that is, while the app is not actively being used). There are several ways to implement background tasks in an iOS app, depending on the specific needs of the task. Some options include:</p><ol><li><strong>Background fetch</strong>: This feature of the iOS operating system allows an app to fetch new data or perform other tasks in the background when the app is not actively being used. To implement background fetch, you need to enable the “Background fetch” capability in the app’s Xcode project, and implement the <strong>application(_:performFetchWithCompletionHandler:)</strong> method in the app&#39;s <strong>UIApplicationDelegate</strong>.</li><li><strong>Background tasks</strong>: The <strong>BGTaskScheduler</strong> framework allows you to schedule background tasks that are executed when the app is in the background. You can use this framework to schedule tasks to run at specific intervals or at specific times, or you can register for specific events that trigger the task.</li></ol><p>Let’s Discuss Background Fetch in this Article.</p><p><strong>To implement background fetch in an iOS app, you need to do the following:</strong></p><ol><li>Enable the “Background fetch” capability in the app’s Xcode project. To do this, open the project’s “Signing &amp; Capabilities” tab, and turn on the <strong>“Background Modes” </strong>option. Then, check the “Background fetch” checkbox.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8Pss7LMdGM09imOTZ8qdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ytdZUkBpo5Hz6WYbjO1ZMQ.png" /></figure><p>2. In the app’s <strong>UIApplicationDelegate</strong>, implement the <strong>application(_:performFetchWithCompletionHandler:)</strong> method. This method is called by the system when it wants to fetch new data for the app.</p><pre>func application(_ application: UIApplication, performFetchWithCompletionHandler completionhandler: @escaping (UIBackgroundFetchResult) -&gt; Void) {<br>    // Perform the background fetch here.<br>    // When the fetch is complete, call the completion handler with the appropriate UIBackgroundFetchResult value.<br>    completionHandler(.newData)<br>}</pre><p>3. In the <strong>performFetchWithCompletionHandler</strong> method, perform the desired background task (such as fetching new data from a server). Be sure to call the completion handler when the task is finished, passing in the <strong>UIBackgroundFetchResult</strong> value that indicates the result of the fetch.</p><p>It’s important to note that iOS places strict limits on the amount of time that an app can spend executing code in the background, and apps that exceed these limits may be terminated. Therefore, it’s important to design background tasks to be as efficient as possible and to only perform the necessary work while in the background.</p><p><strong><em>If you liked this, click the 💚 and give a clap on this post as much as you can below so other people will see this here on Medium. If you have any queries or suggestions, feel free to comment or hit me on </em></strong><a href="https://twitter.com/b_banzara"><strong><em>Twitter</em></strong></a><strong><em>, or </em></strong><a href="https://www.linkedin.com/in/rranjanchchn/"><strong><em>Linkedin</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ed92eb11997" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/ios-interview-background-fetch-background-task-5ed92eb11997">iOS Interview: Background Fetch || Background Task</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Design Pattern [Box Design Pattern] — Write better code]]></title>
            <link>https://medium.com/codex/ios-design-pattern-box-design-pattern-write-better-code-8d7369ca725?source=rss-4a4cf29301a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d7369ca725</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[observables]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Ravi Ranjan]]></dc:creator>
            <pubDate>Mon, 12 Dec 2022 21:41:39 GMT</pubDate>
            <atom:updated>2022-12-20T10:59:56.290Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS Design Pattern [Box Design Pattern] — Write better code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*794W1P5gVlfU71HUCyScVg.jpeg" /></figure><p>The box pattern is a design pattern in Swift that allows you to encapsulate a value in a box so that it can be mutated by reference. This can be useful when you need to pass a value to a function or method, but you want the function or method to be able to mutate the value.</p><p>Here’s an example of how to use the box pattern in Swift:</p><pre>struct Box&lt;T&gt; {<br>    var value: T<br><br>    init(_ value: T) {<br>        self.value = value<br>    }<br>}<br><br>func increment(box: Box&lt;Int&gt;) {<br>    box.value += 1<br>}<br><br>var number = Box(1)<br>increment(box: number)<br>print(number.value) // 2</pre><p>In this code, we define a Box struct that takes a generic type T, which represents the type of the value that the box will hold. The Box struct has a single property, value, which is of type T.</p><p>We then define an increment(box:) function, which takes a Box object as an argument and increments the value property of the Box by one.</p><p>Next, we create a Box object called a number, which contains the value 1. We then call the increment(box:) function, passing the number box as an argument. This causes the value property of the number box to be incremented by one, so its value becomes 2. Finally, we print the value of the number box, which prints 2.</p><p>With the box pattern, we can pass a value to a function or method, and the function or method can mutate the value by reference. This allows us to avoid using inout parameters and to write more expressive and readable code.</p><p><strong><em>If you liked this, click the 💚 and give a clap on this post as much as you can below so other people will see this here on Medium. If you have any queries or suggestions, feel free to comment or hit me on </em></strong><a href="https://twitter.com/b_banzara"><strong><em>Twitter</em></strong></a><strong><em>, or </em></strong><a href="https://www.linkedin.com/in/rranjanchchn/"><strong><em>Linkedin</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d7369ca725" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/ios-design-pattern-box-design-pattern-write-better-code-8d7369ca725">iOS Design Pattern [Box Design Pattern] — Write better code</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Interview: Lazy Property [What and when not to use Lazy property]]]></title>
            <link>https://medium.com/codex/ios-interview-lazy-property-what-and-when-not-to-use-lazy-property-5d621773fc5c?source=rss-4a4cf29301a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d621773fc5c</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-interview-question]]></category>
            <category><![CDATA[lazy-property]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ravi Ranjan]]></dc:creator>
            <pubDate>Mon, 12 Dec 2022 10:36:30 GMT</pubDate>
            <atom:updated>2025-05-27T13:13:50.197Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2P-FN83wx6dokY0Av1rVqQ.png" /></figure><p>In Swift, a lazy variable is a variable whose initial value is not calculated until the first time it is accessed. Lazy variables are useful when the initial value of a variable is expensive to compute, or when it is not needed until it is actually used in the code.</p><p>Here’s an example of how to create a lazy variable in Swift:</p><pre>class HeavilyComputation {<br>    // A heavy object that takes a long time to initialize<br>}<br><br>class MyClass {<br>    lazy var heavilyComputationObject = HeavilyComputation()<br><br>    func doSomething() {<br>        // Use the heavy object<br>        heavyObject.doSomething()<br>    }<br>}</pre><p>in this code, we define a <strong>HeavilyComputation</strong> class that represents an object that takes a long time to initialize. We then define a <strong>MyClass</strong> class that has a <strong>HeavilyComputation</strong> property, which is of type <strong>HeavilyComputation</strong>. We use the <strong>lazy</strong> keyword to mark the <strong>HeavilyComputation</strong> property as a lazy variable.</p><p>When an instance of the <strong>MyClass</strong> class is created, the <strong>HeavilyComputation</strong> property is not initialized until it is accessed for the first time. This means that the <strong>HeavyObject</strong> instance is not created until the <strong>doSomething</strong>() method is called, and the <strong>HeavilyComputation</strong> instance is only created if it is actually needed.</p><p>With this implementation, we can avoid the overhead of initializing the <strong>HeavilyComputation</strong> property unless it is actually needed. This can improve the performance and efficiency of our code, and it can make our code more readable and maintainable.</p><h3>When we should not use Lazy Property?</h3><p>Lazy properties are a useful feature in Swift, but they should be used with caution. In general, you should not use lazy properties when the initial value of the property is not computationally expensive, or when the property is accessed frequently and it would be more efficient to compute its initial value upfront.</p><p>Here are some reasons why you might not want to use lazy properties:</p><blockquote>1. Lazy properties add an extra level of indirection to your code, which can make it more difficult to understand and debug.</blockquote><blockquote>2. Lazy properties can introduce unexpected behavior and race conditions if they are accessed from multiple threads simultaneously. Below example demonstrate the race condition.<br>Here when we will initialize the class MyClass and then try to access the value as normal condition it should print <strong>⛏️ Initializing value… </strong>once<strong> </strong>But<strong> on concurrent condition </strong>it will print it multiple time.</blockquote><pre>import Foundation<br><br>class MyClass {<br>    lazy var value: Int = {<br>        print(&quot;⛏️ Initializing value...&quot;)<br>        return Int.random(in: 1...1000)<br>    }()<br>}<br><br>let obj = MyClass()<br><br>DispatchQueue.concurrentPerform(iterations: 10) { _ in<br>    let v = obj.value<br>    print(&quot;✅ Got value: \(v)&quot;)<br>}</pre><blockquote>3. Lazy properties can make your code less predictable since the initial value of the property will not be computed until it is actually accessed in the code.</blockquote><p>In general, you should only use lazy properties when the initial value of the property is computationally expensive, and when it is not needed until it is actually accessed in the code. Otherwise, you should use a regular property and compute its initial value upfront.</p><p><strong><em>If you liked this, click the 💚 and give a clap on this post as much as you can below so other people will see this here on Medium. If you have any queries or suggestions, feel free to comment or hit me on </em></strong><a href="https://twitter.com/b_banzara"><strong><em>Twitter</em></strong></a><strong><em>, or </em></strong><a href="https://www.linkedin.com/in/rranjanchchn/"><strong><em>Linkedin</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d621773fc5c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/ios-interview-lazy-property-what-and-when-not-to-use-lazy-property-5d621773fc5c">iOS Interview: Lazy Property [What and when not to use Lazy property]</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Interview: Method Dispatch (Dynamic_Dispatch & Static Dispatch)]]></title>
            <link>https://medium.com/codex/ios-interview-method-dispatch-dynamic-dispatch-static-dispatch-2ecd75891f82?source=rss-4a4cf29301a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ecd75891f82</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[dynamic-dispatch]]></category>
            <category><![CDATA[ios-interview-question]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Ravi Ranjan]]></dc:creator>
            <pubDate>Sun, 11 Dec 2022 06:22:05 GMT</pubDate>
            <atom:updated>2022-12-21T01:17:39.856Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*d-8Iwe3IDI9-3sLh69ao8Q.jpeg" /></figure><p>I have a very fundamental question for all the readers who want to understand the Method dispatch (Dynamic_Dispatch &amp; Static Dispatch).</p><p>Method dispatch is the process of selecting the implementation of a method to be executed at runtime. In object-oriented languages like Swift, method dispatch is used to support polymorphism, which allows objects of different classes to respond to the same method call in different ways.</p><p>There are two main types of method dispatch: <strong>dynamic dispatch</strong> and <strong>static dispatch.</strong></p><p>Dynamic dispatch is a type of method dispatch in which the implementation of a method is selected at runtime based on the type of object that is receiving the method call. Dynamic dispatch is also known as <strong>late binding or runtime binding </strong>because the method implementation is not bound to the method call until runtime.</p><p>Dynamic dispatch is often used in languages that support inheritance and polymorphism because it allows objects of different classes to respond to the same method call in different ways. In dynamic dispatch, the method implementation that is selected at runtime is determined by the type of object that is receiving the method call, not by the type of object that is calling the method.</p><pre>class Animal {<br>    func makeNoise() {<br>        // Default implementation<br>    }<br>}<br><br>class Dog: Animal {<br>    override func makeNoise() {<br>        print(&quot;Woof!&quot;)<br>    }</pre><p><strong><em>If you liked this, click the 💚 and give a clap on this post as much as you can below so other people will see this here on Medium. If you have any queries or suggestions, feel free to comment or hit me on </em></strong><a href="https://twitter.com/b_banzara"><strong><em>Twitter</em></strong></a><strong><em>, or </em></strong><a href="https://www.linkedin.com/in/rranjanchchn/"><strong><em>Linkedin</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ecd75891f82" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/ios-interview-method-dispatch-dynamic-dispatch-static-dispatch-2ecd75891f82">iOS Interview: Method Dispatch (Dynamic_Dispatch &amp; Static Dispatch)</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[iOS Interview] Operation Queue -concurrency]]></title>
            <link>https://medium.com/codex/ios-interview-operation-queue-interview-answer-20cd0b4bdc5?source=rss-4a4cf29301a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/20cd0b4bdc5</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Ravi Ranjan]]></dc:creator>
            <pubDate>Fri, 09 Dec 2022 20:33:47 GMT</pubDate>
            <atom:updated>2022-12-11T13:05:06.567Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nY3kbUFbd-x2G4lDUBtxJg.jpeg" /></figure><p>An operation queue is a fundamental class in the Foundation framework that is used to manage the execution of operations in your application. An operation is a discrete unit of work that can be executed concurrently or independently of other operations.</p><p>In Swift, you can create an operation queue using the OperationQueue class. Here&#39;s an example of how to create an operation queue:</p><pre>let queue = OperationQueue()</pre><p>In this code, we create an OperationQueue object and assign it to a constant called queue. We can then use this queue to manage the execution of operations in our code.</p><p>To add an operation to the queue, you can use the addOperation(_:) method of the OperationQueue class. Here&#39;s an example of how to add an operation to the queue:</p><pre>let queue = OperationQueue()<br><br>let operation = BlockOperation {<br>    // Your Task<br>}<br><br>queue.addOperation(operation)</pre><p>n this code, we create an OperationQueue object and an Operation object using the BlockOperation class. The BlockOperation class is a concrete subclass of the Operation class that allows you to define a block of code to be executed as the operation&#39;s main task.</p><p>Next, we use the addOperation(_:) method to add the operation object to the queue. This causes the operation to be executed by the queue, and the code block that we defined in the BlockOperation initializer will be executed as the operation&#39;s main task.</p><p>With this implementation, you can use an operation queue to manage the execution of operations in your code. You can add operations to the queue, and the queue will take care of executing the operations and managing their dependencies and concurrency. This allows you to write efficient and scalable applications that can take advantage of the power of concurrent and parallel execution.</p><p><strong><em>If you liked this, click the 💚 and give a clap on this post as much as you can below so other people will see this here on Medium. If you have any queries or suggestions, feel free to comment or hit me on </em></strong><a href="https://twitter.com/b_banzara"><strong><em>Twitter</em></strong></a><strong><em>, or </em></strong><a href="https://www.linkedin.com/in/rranjanchchn/"><strong><em>Linkedin</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20cd0b4bdc5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/ios-interview-operation-queue-interview-answer-20cd0b4bdc5">[iOS Interview] Operation Queue -concurrency</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Interview: Computed Property]]></title>
            <link>https://medium.com/codex/ios-interview-preparation-computed-property-a229a787e954?source=rss-4a4cf29301a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a229a787e954</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[computed-property]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ravi Ranjan]]></dc:creator>
            <pubDate>Wed, 28 Sep 2022 21:59:58 GMT</pubDate>
            <atom:updated>2022-12-11T13:05:00.750Z</atom:updated>
            <content:encoded><![CDATA[<p>Before Jumping into Computed property first let’s understand what is Property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0f5ku40OoC1Hl0fLMujF2g.png" /></figure><p>Properties are values associated with a class, struct, or enumeration type in Swift. An example of this is for a Car we have Wheels, Doors, HeadLight, Steering, etc are the properties by which we can build a car. these properties can be constant or can vary in nature depending upon the part of the instance. eg. A car can have 2 or 4 doors so it is a variable but a car can have only one steering so it is constant in nature.</p><p>Below is the bone structure for a car yes we can have other properties as well but for the sake of simpleness, I just took these five of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NiRJ1n_25l9ZyY1ordnZUg.png" /></figure><p><strong>Computed</strong> properties are the property that does not store the value rather than calculate the value. so as the computed property does not store a value it provides a getter to retrieve an optional<strong> <em>setter to set other properties and values indirectly.</em></strong></p><blockquote>Computed properties are the properties that don’t get initialised while object creation or constructor is called. They get computed every time the property is accessed.</blockquote><p>let’s understand with this an example of our car class.</p><p>let’s suppose we want to access the beam length of the headlight and we have a simple formula:<br>beamLength = numberOfLights * 10</p><p>so what we can do is we can have a function that can calculate the beam length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*1k81npKtsjXx93LAyJLEBQ.png" /></figure><p>Now this is a very simple calculation and it does not require any parameter, and no validation is required also it will not throw any kind of error so instead of creating a function we can create a computed property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*Om7VKrAePzkzMouLuGLRKw.png" /></figure><blockquote>A computed property is effectively just a function call that happens to belong to your struct mean Computed property is similar to a normal function which will return a value of certain type but it can’t accept parameters.</blockquote><p>this computed property will act similar to the function we have written but is so concise. and to validate more if you have created a computed property with some name you can’t create a function with the same name unless you modify the parameters.</p><p>Please find great article below for computed property :</p><ul><li><a href="https://www.donnywals.com/what-are-computed-properties-in-swift-and-when-should-you-use-them/">What are computed properties in Swift and when should you use them?</a></li><li><a href="https://www.avanderlee.com/swift/computed-property/">What is a Computed Property in Swift?</a></li><li><a href="https://agrawalsuneet.github.io/blogs/computed-property-in-swift/">Computed Property in Swift</a></li></ul><p><strong><em>If you liked this, click the 💚 and give a clap on this post as much as you can below so other people will see this here on Medium. If you have any queries or suggestions, feel free to comment or hit me on </em></strong><a href="https://twitter.com/b_banzara"><strong><em>Twitter</em></strong></a><strong><em>, or </em></strong><a href="https://www.linkedin.com/in/rranjanchchn/"><strong><em>Linkedin</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a229a787e954" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/ios-interview-preparation-computed-property-a229a787e954">iOS Interview: Computed Property</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>