<?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 Ranga C on Medium]]></title>
        <description><![CDATA[Stories by Ranga C on Medium]]></description>
        <link>https://medium.com/@ranga.c222?source=rss-c4448436c321------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rGwLNA_KDrqtOYU41Z_2nQ.jpeg</url>
            <title>Stories by Ranga C on Medium</title>
            <link>https://medium.com/@ranga.c222?source=rss-c4448436c321------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:41:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ranga.c222/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[Routing Class: A Clean Approach to Navigation]]></title>
            <link>https://medium.com/@ranga.c222/routing-class-a-clean-approach-to-navigation-692f1f947337?source=rss-c4448436c321------2</link>
            <guid isPermaLink="false">https://medium.com/p/692f1f947337</guid>
            <category><![CDATA[router]]></category>
            <category><![CDATA[uinavigationcontroller]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[storyboard]]></category>
            <dc:creator><![CDATA[Ranga C]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 13:55:58 GMT</pubDate>
            <atom:updated>2025-07-29T13:55:58.277Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EcQwcLcHdEm91wJSciKSUQ.png" /></figure><p><strong>Elegant Navigation in UIKit with a Centralized Router</strong></p><p><strong>Introduction</strong></p><p>Managing navigation flows in UIKit can become messy as your app grows. Storyboard segues and direct UINavigationController interactions often lead to tightly coupled view controllers. In this article, I’ll introduce a <strong>centralized Router pattern</strong> that:</p><p>✅ <strong>Decouples navigation logic</strong> from view controllers<br> ✅ <strong>Maintains a type-safe navigation stack</strong><br> ✅ <strong>Supports deep linking</strong> (navigating to specific screens)<br> ✅ <strong>Works seamlessly with Storyboards</strong></p><p>The Problem with Traditional UIKit Navigation</p><p>In typical UIKit apps, navigation is handled in one of these ways:</p><p>Storyboard Segues</p><p>Tightly couples view controllers</p><p>Hard to modify flows programmatically</p><p>Manual UINavigationController Pushes/Pops</p><p>Navigation logic scattered across view controllers</p><p>No centralized tracking of the navigation stack</p><p>Coordinators (Good, but Complex for Small Apps)</p><p>Overkill for simple navigation flows</p><p>Requires more boilerplate</p><p>What if we could get the benefits of coordinators with minimal setup?</p><p>2. Introducing the Router Pattern</p><p>The Router is a centralized class that:</p><p>Manages navigation stack (navPath)</p><p>Handles pushing/popping view controllers</p><p>Supports deep linking (jumping to specific screens)</p><p><strong>Key Components</strong></p><ol><li>Router<strong> Class</strong></li></ol><pre>// Router.swift<br>import UIKit<br><br>final class Router {<br>    <br>    enum AuthFlow: String {<br>        case login<br>        case forgotPassword<br>        case emailSent<br>        case profile<br>    }<br>    <br>    private(set) var navPath: [AuthFlow] = []<br>    private weak var navigationController: UINavigationController?<br>    private let storyboard: UIStoryboard<br>    <br>    init(navigationController: UINavigationController, storyboard: UIStoryboard = UIStoryboard(name: &quot;Main&quot;, bundle: nil)) {<br>        self.navigationController = navigationController<br>        self.storyboard = storyboard<br>    }<br>    <br>    func navigate(to destination: AuthFlow) {<br>        navPath.append(destination)<br>        <br>        let viewController: UIViewController = storyboard.instantiateViewController(withIdentifier: destination.rawValue)<br>        viewController.restorationIdentifier = destination.rawValue // ✅ add this<br><br>        // Inject router into the view controller<br>        if let routableVC = viewController as? Routable {<br>            routableVC.router = self<br>        }<br>        <br>        navigationController?.pushViewController(viewController, animated: true)<br>    }<br>    <br>    func navigateBack() {<br>        guard !navPath.isEmpty else { return }<br>        navPath.removeLast()<br>        navigationController?.popViewController(animated: true)<br>    }<br>    <br>    func popToRoot() {<br>        navPath.removeAll()<br>        navigationController?.popToRootViewController(animated: true)<br>    }<br>    <br>    // New method to navigate to specific view controller<br>    func navigateToSpecificViewController(_ destination: AuthFlow) {<br>        guard let navController = navigationController else {<br>            return<br>        }<br><br>        // Try to find an existing VC in the stack matching the destination&#39;s restorationIdentifier<br>        if let targetVC = navController.viewControllers.first(where: {<br>            $0.restorationIdentifier == destination.rawValue<br>        }) {<br>            // Sync navPath with actual navigation stack after popping<br>            navController.popToViewController(targetVC, animated: true)<br>            navPath = navController.viewControllers.compactMap {<br>                guard let id = $0.restorationIdentifier else { return nil }<br>                return AuthFlow(rawValue: id)<br>            }<br><br>        } else {<br>            navigate(to: destination)<br>        }<br>    }<br><br>}<br><br>protocol Routable: AnyObject {<br>    var router: Router? { get set }<br>}</pre><p>Usage in View Controllers:</p><p>App Delegate</p><pre>import UIKit<br><br>@main<br>class AppDelegate: UIResponder, UIApplicationDelegate {<br><br>    var window: UIWindow?<br>    var router: Router?<br><br>    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br>        <br>        window = UIWindow(frame: UIScreen.main.bounds)<br>        let storyboard = UIStoryboard(name: &quot;Main&quot;, bundle: nil)<br>        <br>        let navigationController = UINavigationController()<br>        router = Router(navigationController: navigationController, storyboard: storyboard)<br>        <br>        window?.rootViewController = navigationController<br>        window?.makeKeyAndVisible()<br>        <br>        // Start with login screen<br>        router?.navigate(to: .login)<br>        <br>        return true<br>    }<br>}</pre><p>Login ViewController</p><pre>import UIKit<br><br>class LoginViewController: UIViewController, Routable {<br>    var router: Router?<br>    <br>    @IBAction func forgotPasswordTapped(_ sender: UIButton) {<br>        router?.navigate(to: .forgotPassword)<br>    }<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>       restorationIdentifier = Router.AuthFlow.login.rawValue <br>    }<br>}</pre><p>Forgot Password ViewController</p><pre>import UIKit<br><br>class ForgotPasswordViewController: UIViewController, Routable {<br>    var router: Router?<br>    <br>    @IBAction func sendInstructionsTapped(_ sender: UIButton) {<br>        router?.navigate(to: .emailSent)<br>    }<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        restorationIdentifier = Router.AuthFlow.forgotPassword.rawValue // Optional, but helpful<br>    }<br>}</pre><p>Email Sent ViewController</p><pre>import UIKit<br><br>class EmailSentViewController: UIViewController, Routable {<br>    var router: Router?<br>    <br>// Navigate to Root view controller<br>    @IBAction func loginLaterTapped(_ sender: UIButton) {<br>        router?.popToRoot()<br>    }<br>    <br>    <br>    @IBAction func profileTapped(_ sender: UIButton) {<br>        router?.navigate(to: .profile)<br>    }<br>    <br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        restorationIdentifier = Router.AuthFlow.emailSent.rawValue // Optional, but helpful<br>    }<br>}</pre><p>Profile View controller</p><pre>// ProfileViewController.swift<br>import UIKit<br><br>class ProfileViewController: UIViewController, Routable {<br>    var router: Router?<br>    <br>    @IBAction func resetPasswordTapped(_ sender: UIButton) {<br>// Navigate(Jumping) to Specific view controller<br>        router?.navigateToSpecificViewController(.forgotPassword)<br>    }<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        restorationIdentifier = Router.AuthFlow.profile.rawValue // Optional, but helpful<br>    }<br>}</pre><p>Output:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHeySurxO5iA&amp;type=text%2Fhtml&amp;schema=google&amp;display_name=YouTube&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHeySurxO5iA" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccabedcbbd8dd83671f049c9c35d378a/href">https://medium.com/media/ccabedcbbd8dd83671f049c9c35d378a/href</a></iframe><p><strong>Key Benefits</strong></p><p>✅ <strong>Decoupled Navigation</strong></p><p>✅ <strong>Type-Safe Routing</strong></p><p>✅ <strong>Deep Linking Support</strong></p><p>✅ <strong>Works with Storyboards</strong></p><p>✅ <strong>Clear Stack Management</strong></p><p>Why This Matters</p><ul><li>Scalable: Add new screens by just extending AuthFlow.</li><li>Maintainable: Change navigation flows in one place (Router).</li><li>Debug-Friendly: navPath logs the exact screen history.</li></ul><p>This turns UIKit navigation into a predictable, modular system — perfect for auth flows, onboarding, or deep linking. 🚀</p><p>Thanks for reading…Happy coding..😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=692f1f947337" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference Between popLast() & removeLast() in Swift]]></title>
            <link>https://medium.com/@ranga.c222/difference-between-poplast-removelast-in-swift-78b3b70ce494?source=rss-c4448436c321------2</link>
            <guid isPermaLink="false">https://medium.com/p/78b3b70ce494</guid>
            <category><![CDATA[swift-array]]></category>
            <category><![CDATA[optionalhandling]]></category>
            <category><![CDATA[swift-collections-guide]]></category>
            <category><![CDATA[poplast]]></category>
            <category><![CDATA[removelast]]></category>
            <dc:creator><![CDATA[Ranga C]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 06:56:08 GMT</pubDate>
            <atom:updated>2024-11-26T06:56:08.089Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*qiOHzcsXyYNBBeEI.png" /></figure><p>In Swift, both popLast() and removeLast() are used to remove elements from the end of a collection (like an array). However, there are important differences in how they behave:</p><h4><strong>1. </strong><strong>popLast()</strong></h4><ul><li><strong>Type</strong>: A <strong>safe</strong> method.</li><li><strong>Return Value</strong>: Returns an optional (Element?).</li><li>If the collection is not empty, it removes and returns the last element.</li><li>If the collection is empty, it returns nil.</li></ul><p><strong>Behavior</strong>: It doesn’t crash if called on an empty collection.</p><p><strong>Use Case</strong>: Use popLast() when you’re unsure if the collection is empty and want to avoid potential crashes.</p><pre>var array = [1, 2, 3]<br>if let lastElement = array.popLast() {<br>    print(&quot;Removed: \(lastElement)&quot;) // Output: Removed: 3<br>} else {<br>    print(&quot;Array is empty&quot;)<br>}<br><br>print(array) // Output: [1, 2]<br><br>array.popLast() // Removes 2<br>array.popLast() // Removes 1<br>array.popLast() // Returns nil (safe, no crash)</pre><h4>2. removeLast()</h4><ul><li><strong>Type</strong>: An <strong>unsafe</strong> method.</li><li><strong>Return Value</strong>: Returns the non-optional last element (Element).</li><li><strong>Behavior</strong>: Crashes if called on an empty collection.</li><li><strong>Use Case</strong>: Use removeLast() only when you are certain that the collection is not empty.</li></ul><pre>var array = [1, 2, 3]<br>let lastElement = array.removeLast()<br>print(&quot;Removed: \(lastElement)&quot;) // Output: Removed: 3<br>print(array) // Output: [1, 2]<br><br>// Attempting to remove from an empty array<br>array.removeLast() // Removes 2<br>array.removeLast() // Removes 1<br>array.removeLast() // CRASH: Fatal error: Can&#39;t removeLast() from an empty array</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNdITkL7c2I8VTjw4t0khQ.png" /></figure><h3>Recommendation</h3><ul><li>Use popLast() for safety when the collection might be empty.</li><li>Use removeLast() when performance matters and you&#39;re confident the collection is not empty.</li></ul><p>Thanks for reading…Happy coding..😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78b3b70ce494" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Swift Concurrency]]></title>
            <link>https://medium.com/@ranga.c222/mastering-swift-concurrency-082757e86a1a?source=rss-c4448436c321------2</link>
            <guid isPermaLink="false">https://medium.com/p/082757e86a1a</guid>
            <category><![CDATA[operationqueue]]></category>
            <category><![CDATA[semaphore]]></category>
            <category><![CDATA[dispatchgroup]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <dc:creator><![CDATA[Ranga C]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 10:20:30 GMT</pubDate>
            <atom:updated>2024-11-20T07:19:36.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*r4gW7cj_9emApoq0.jpeg" /></figure><h3>Synchronizing Tasks with Semaphores, Dispatch Groups, and Operation Queues, Async-Await</h3><p>When working with Swift’s concurrency features, managing the precise order of tasks can be challenging, especially if we want two functions to alternate their execution. In this article, we’ll walk through a common exercise — alternating the printing of numbers and letters using multiple concurrency methods in Swift. This exercise not only highlights various concurrency tools like DispatchSemaphore, DispatchGroup, and OperationQueue, but it also showcases techniques for managing task order in concurrent environments.</p><h3>Project Setup</h3><p>Let’s assume you’re working in a simple Swift project, and you want to build a function that prints numbers and letters in the following alternating sequenceCopy code.</p><pre>1, A, 2, B, 3, C, ... 26, Z</pre><p>To accomplish this, we’ll cover three primary methods:</p><ol><li>Using DispatchSemaphore</li><li>Using DispatchGroup and serial DispatchQueue</li><li>Using OperationQueue and BlockOperation</li></ol><p>Let’s dive into each approach, step-by-step.</p><h3>Method 1: Using DispatchSemaphore</h3><p>DispatchSemaphore provides a simple way to control access to a resource. By initializing semaphores with specific values, you can control how tasks interact with each other. Here’s how we can achieve alternating behavior using DispatchSemaphore in Swift:</p><h3>Code Implementation with DispatchSemaphore</h3><pre>class ViewController: UIViewController {<br><br>    let numberSemaphore = DispatchSemaphore(value: 1)<br>    let letterSemaphore = DispatchSemaphore(value: 0)<br>    let numberQueue = DispatchQueue(label: &quot;com.number&quot;)<br>    let letterQueue = DispatchQueue(label: &quot;com.letter&quot;)<br>    <br>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Asynchronously start the two functions<br>        numberQueue.async {<br>            self.printNumbers()<br>        }<br>        <br>        letterQueue.async {<br>            self.printAlphabets()<br>        }<br>        <br>    }<br>    func printNumbers() {<br>        for number in 1...26 {<br>            numberSemaphore.wait()<br>            print(number, terminator: &quot;,&quot;)<br>            letterSemaphore.signal()<br>        }<br>    }<br>    <br>    func printAlphabets() {<br>        for letter in 0..&lt;26 {<br>            letterSemaphore.wait()<br>            print(Character(UnicodeScalar(65 + letter)!), terminator: &quot;,&quot;)<br>            numberSemaphore.signal()<br>        }<br>    }<br>}</pre><h3>Explanation</h3><ol><li><strong>Semaphore Initialization</strong>: numberSemaphore starts with a value of 1, while letterSemaphore is initialized to 0, allowing printNumbers() to proceed first.</li><li><strong>Alternation Control</strong>: After printNumbers() prints a number, it calls letterSemaphore.signal() to wake printAlphabets(). Then printAlphabets() waits for numberSemaphore to signal it back after printing a letter.</li><li><strong>Execution Time Measurement</strong>: We start the timer before launching the tasks and then measure the time after all operations are complete. This is helpful to gauge performance and test optimizations.</li></ol><h3>Method 2: Using DispatchGroup with a Serial Queue</h3><p>Another way to alternate execution is by using DispatchGroup with a single serial queue. This allows us to control task order without explicitly signaling between functions.</p><h3>Code Implementation with DispatchGroup and Serial Queue</h3><pre>class ViewController: UIViewController {<br><br>let queue = DispatchQueue(label: &quot;com.alternatingPrint&quot;, attributes: .concurrent)<br>    let group = DispatchGroup()<br>   <br> override func viewDidLoad() {<br>        super.viewDidLoad()        <br>        // Begin alternating prints in serial fashion<br>        queue.async {<br>            self.printAlternating()<br>        }<br>    }<br>    func printAlternating() {<br>        for i in 1...26 {<br>            group.enter()<br>            queue.async {<br>                print(i, terminator: &quot;,&quot;)<br>                self.group.leave()<br>            }<br>            group.wait()<br>            group.enter()<br>            queue.async {<br>                print(Character(UnicodeScalar(64 + i)!), terminator: &quot;,&quot;)<br>                self.group.leave()<br>            }<br>            group.wait()<br>        }<br>    }<br>}</pre><h3>Explanation</h3><ol><li><strong>Single Serial Queue</strong>: The DispatchQueue ensures that printAlternating() executes in a serial manner.</li><li><strong>DispatchGroup for Synchronization</strong>: group.enter() and group.leave() control each print, ensuring that we alternate between numbers and letters.</li><li><strong>Waiting</strong>: The group.wait() command pauses the loop until the current task completes, helping maintain alternation.</li></ol><h3>Method 3: Using OperationQueue and BlockOperation</h3><p>An OperationQueue with BlockOperation allows for orderly execution of tasks. By setting dependencies between BlockOperation tasks, we can control their order.</p><h3>Code Implementation with OperationQueue</h3><pre>class ViewController: UIViewController {<br><br>let operationQueue = OperationQueue()<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        operationQueue.maxConcurrentOperationCount = 1 // Serial execution<br>        <br>        for i in 1...26 {<br>            let numberOperation = BlockOperation {<br>                print(i, terminator: &quot;,&quot;)<br>            }<br>            <br>            let letterOperation = BlockOperation {<br>                print(Character(UnicodeScalar(64 + i)!), terminator: &quot;,&quot;)<br>            }<br>            <br>            // Make letterOperation depend on numberOperation<br>            letterOperation.addDependency(numberOperation)<br>            <br>            operationQueue.addOperation(numberOperation)<br>            operationQueue.addOperation(letterOperation)<br>        }<br>    }<br>}</pre><h3>Explanation</h3><ol><li><strong>Serial Operation Queue</strong>: Setting maxConcurrentOperationCount = 1 ensures serial execution.</li><li><strong>Task Dependency</strong>: By adding letterOperation as a dependent of numberOperation, each letter is printed only after its corresponding number.</li><li><strong>Execution Time Measurement</strong>: As with the previous methods, we measure the execution time after a slight delay to ensure completion.</li></ol><h3>Method 4: Using Async/Await</h3><p>With async and await, we can create two asynchronous tasks that wait for each other in sequence to alternate printing. By using await within the print functions, we can control the order of execution without relying on semaphores or other concurrency primitives.</p><h3>Code Implementation with Async/Await</h3><pre>class ViewController: UIViewController { <br>    <br>    var startTime = DispatchTime(uptimeNanoseconds: 0)<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        Task {<br>            await self.printAlternating()<br>        }<br>    }<br>    <br>    func printAlternating() async {<br>        <br>        for i in 1...26 {<br>            print(i, terminator: &quot;,&quot;)<br>            await Task.yield()<br>            <br>            let letter = Character(UnicodeScalar(64 + i)!)<br>            print(letter, terminator: &quot;,&quot;)<br>            await Task.yield()<br>            <br>        }<br>    }<br>    <br>}</pre><h3>Explanation</h3><ol><li><strong>Async/Await Control</strong>: The printAlternatingNumbersAndLetters function is marked as async, which allows each print task to be suspended and resumed in order.</li><li><strong>Alternating Execution</strong>: The await keyword allows each function to complete its task before the next one begins, ensuring that numbers and letters alternate.</li><li><strong>Simulated Delay</strong>: Task.sleep introduces a slight delay to simulate processing time, which can help observe the alternation effect in real time.</li></ol><p><strong><em>conclusion</em></strong></p><blockquote>In this article, we explored multiple ways to implement alternating task execution in Swift, specifically by printing numbers and letters sequentially. By examining various approaches — using semaphores, dispatch groups, operation queues, and the modern async/await feature—we’ve seen how Swift provides a rich toolkit for handling concurrency and synchronization.</blockquote><p>Thanks for reading…Happy coding..😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=082757e86a1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Any & AnyObject in iOS]]></title>
            <link>https://medium.com/@ranga.c222/any-anyobject-in-ios-17da20f6c3d2?source=rss-c4448436c321------2</link>
            <guid isPermaLink="false">https://medium.com/p/17da20f6c3d2</guid>
            <category><![CDATA[any-and-anyobject]]></category>
            <category><![CDATA[any-vs-anyobject]]></category>
            <category><![CDATA[anies]]></category>
            <category><![CDATA[anyobject]]></category>
            <category><![CDATA[any-vs-anyobject-swift]]></category>
            <dc:creator><![CDATA[Ranga C]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 05:14:23 GMT</pubDate>
            <atom:updated>2023-09-11T05:14:23.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*VanzK7BCXMzx-xTLG4FqCg.jpeg" /></figure><p>Any and AnyObject are two special type aliases in Swift that allow you to cast any value to a specific type.</p><p>Any is used to represent any type, including functions and optional types, whereas AnyObject is used to represent any instance of a class type.</p><p>Here’s an example using Any:</p><pre>let mixedArray: [Any] = [1, &quot;Hello&quot;, true, 2.0]<br>for item in mixedArray {<br>  switch item {<br>  case let x as Int:<br>    print(&quot;Int: \(x)&quot;)<br>  case let x as String:<br>    print(&quot;String: \(x)&quot;)<br>  case let x as Bool:<br>    print(&quot;Bool: \(x)&quot;)<br>  case let x as Double:<br>    print(&quot;Double: \(x)&quot;)<br>  default:<br>    print(&quot;Unknown type&quot;)<br>  }<br>}</pre><p>In this example, an array mixedArray is defined with elements of various types, including Int, String, Bool, and Double. The for loop iterates over the elements of the array and uses a switch statement to perform type casting and determine the type of each element.</p><p>Here’s an example using AnyObject:</p><pre>class Car {}<br>class Song {}</pre><pre>let objectsArray: [AnyObject] = [Car(), Car(), Song()]<br>for item in objectsArray {<br>  if let car = item as? Car {<br>    print(&quot;Car: \(car)&quot;)<br>  } else if let song = item as? Song {<br>    print(&quot;Song: \(song)&quot;)<br>  } else {<br>    print(&quot;Unknown type&quot;)<br>  }<br>}</pre><p>In this example, an array objectsArray is defined with elements of class types, including Car and Song. The for loop iterates over the elements of the array and uses as? operator to perform type casting and determine the type of each element. If the type cast is successful, the appropriate message is printed.</p><h3>Difference Between Any and AnyObject</h3><p>Any is a type in Swift that can represent an instance of any type, including function types. It can be used to store heterogeneous collections of values.</p><p>AnyObject is a type in Swift that can represent an instance of any <em>class</em> type. It can be used to store collections of class instances where the specific class type is unknown.</p><p>The main difference between Any and AnyObject is that Any can represent any type, including value types and function types, while AnyObject can only represent class types.</p><h3>When should we choose Any or AnyObject?</h3><p>It’s a good practice to use AnyObject while you are working with references and use Any when working with value types.</p><p><em>Note: If possible, we should avoid both Any and AnyObject. It’s better to be specific.</em></p><p>Have you any queries? comment on it.😊</p><p>Have you found it useful? clap it 👏🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17da20f6c3d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[THREAD SAFETY IN SWIFT]]></title>
            <link>https://medium.com/@ranga.c222/thread-safety-in-swift-495a88d24d7d?source=rss-c4448436c321------2</link>
            <guid isPermaLink="false">https://medium.com/p/495a88d24d7d</guid>
            <category><![CDATA[dispatchqueue]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Ranga C]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 11:14:56 GMT</pubDate>
            <atom:updated>2023-09-06T11:14:56.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/402/0*IVKi_GHa98KvxFqU" /></figure><p>Thread safety refers to a programming concept where data or resources are accessed and modified in a way that ensures correct behavior and prevents conflicts when multiple threads (concurrent execution units) are working with the same data simultaneously. In multi-threaded environments, without proper thread safety measures, unpredictable and erroneous behavior can occur due to race conditions and data inconsistencies.</p><p>Developers implement thread safety using various techniques, such as locks, semaphores, atomic operations, and synchronization mechanisms. These techniques help control access to shared resources, ensuring that only one thread can modify or access the resource at a time, while others wait or perform their operations without causing conflicts.</p><p>Thread safety is crucial to prevent data corruption, crashes, and unexpected behavior in concurrent programs, and it’s especially important in languages like Swift, where multi-threading is common due to the use of Grand Central Dispatch (GCD) and other concurrency frameworks.</p><h3>Ways to achieve thread safety</h3><p>In Swift, there are several common ways to achieve thread safety when dealing with concurrent programming. Here are some of the most widely used approaches:</p><h3>Serial Queues with GCD:</h3><p>Using Grand Central Dispatch (GCD), you can create serial queues that ensure only one task is executed at a time. This is a straightforward way to achieve thread safety.</p><pre>let serialQueue = DispatchQueue(label: &quot;com.example.serialQueue&quot;)<br>serialQueue.async {<br>    // Perform thread-safe operations<br>}</pre><h3>Concurrent Queues with GCD:</h3><p>Concurrent queues allow multiple tasks to run concurrently, while still managing synchronization. This can be useful for improving performance when multiple threads can work independently.</p><pre>let concurrentQueue = DispatchQueue(label: &quot;com.example.concurrentQueue&quot;, attributes: .concurrent)<br>concurrentQueue.async {<br>    // Perform thread-safe operations<br>}</pre><h3>Dispatch Barrier for Read-Write Access:</h3><p>GCD’s dispatch barriers are useful for implementing read-write locks. They ensure that a block of code executes exclusively when performing write operations while allowing concurrent read operations.</p><pre>let concurrentQueue = DispatchQueue(label: &quot;com.example.concurrentQueue&quot;, attributes: .concurrent)<br>concurrentQueue.async(flags: .barrier) {<br>    // Perform thread-safe write operations<br>}</pre><h3>Atomic Properties:</h3><p>In Swift, you can use atomic properties provided by the AtomicValue type from the Swift Atomics library. These properties ensure thread-safe access to the value they encapsulate.</p><pre>import Atomics<br>var atomicValue = ManagedAtomic&lt;Int&gt;.create(initialValue: 0)<br>let newValue = atomicValue.add(1)</pre><h3>Actor Model (Swift Concurrency):</h3><p>Swift’s concurrency model introduces the actor concept, which encapsulates both data and behavior. Only one task can access an actor’s methods and properties at a time, ensuring thread safety.</p><pre>actor Counter {<br>    private var value = 0<br>    <br>    func increment() {<br>        value += 1<br>    }<br>}    <br>let counter = Counter()<br>await counter.increment()</pre><h3>DispatchSemaphore:</h3><p>A semaphore is a synchronization primitive that allows a certain number of threads to access a resource concurrently. It’s useful when you want to limit the number of concurrent accesses.</p><pre>let semaphore = DispatchSemaphore(value: 2)<br>DispatchQueue.global().async {<br>    semaphore.wait()<br>    // Perform thread-safe operations<br>    semaphore.signal()<br>}</pre><p>Choose the method that best suits your application’s requirements, considering factors like performance, ease of implementation, and compatibility with Swift’s evolving concurrency features. The introduction of Swift Concurrency and the Actor model in recent Swift versions provides powerful tools for achieving thread safety in a more natural and structured way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=495a88d24d7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous Programming with Async/Await in Swift]]></title>
            <link>https://medium.com/@ranga.c222/asynchronous-programming-with-async-await-in-swift-a06c9ee4dd0e?source=rss-c4448436c321------2</link>
            <guid isPermaLink="false">https://medium.com/p/a06c9ee4dd0e</guid>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[concurrency-in-swift]]></category>
            <dc:creator><![CDATA[Ranga C]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 10:05:11 GMT</pubDate>
            <atom:updated>2023-08-25T10:09:10.587Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r4gW7cj_9emApoq0.jpeg" /></figure><p><strong>Introduction</strong></p><p>Asynchronous programming is a crucial aspect of modern software development, especially in applications that require responsive and efficient handling of tasks like network requests, file I/O, and more. However, traditional approaches to handling asynchronous code, like completion handlers and delegates, can lead to complex and error-prone code. To address these issues, Swift introduced the async/await paradigm, a more concise and intuitive way to write asynchronous code. In this article, we will delve into the async/await mechanism in Swift, exploring its benefits, usage, and best practices.</p><p>Understanding Async/Await</p><p>async/await is a programming paradigm that simplifies asynchronous code by making it look and feel more like traditional synchronous code. Instead of using callbacks or delegate methods, developers can write asynchronous code that resembles a sequence of sequential statements. This makes the code more readable, maintainable, and less prone to callback hell or nesting.</p><p>Key Concepts</p><ol><li>Async Functions: An asynchronous function is declared using the async keyword before its return type. Such functions can contain the await keyword, which suspends the execution of the function until the awaited asynchronous task is complete.</li><li>Awaiting Tasks: The await keyword is used to pause the execution of an asynchronous function until a given asynchronous task completes. This allows for clean and sequential code without blocking the thread.</li><li>Cancellation: async/await introduces structured concurrency, enabling better control over tasks&#39; lifecycles. Cancellation of tasks becomes more straightforward and less error-prone.</li></ol><p>Benefits of Async/Await</p><ol><li>Readability: Asynchronous code written using async/await is more linear and easier to understand, as it resembles traditional synchronous code. This reduces cognitive load and makes maintenance less challenging.</li><li>Error Handling: Error handling becomes more consistent, as errors can be propagated through the call stack using regular try/catch blocks, just like in synchronous code.</li><li>Debugging: Debugging asynchronous code is simplified, as developers can place breakpoints and inspect variables in a more predictable manner.</li><li>Concurrency Safety: Swift’s async/await enforces safe concurrency by design. Data races and common concurrency issues are mitigated, enhancing the overall stability of the codebase.</li></ol><p>Using Async/Await in Swift</p><p>Let’s explore a basic example of how async/await is used in Swift:</p><pre><br>    func getAverageTemperature() async {<br>        let fetchTask = Task { () -&gt; Double in<br>            let url = URL(string: &quot;https://hws.dev/readings.json&quot;)!<br>            let (data, _) = try await URLSession.shared.data(from: url)<br>            let readings = try JSONDecoder().decode([Double].self, from: data)<br>            let sum = readings.reduce(0, +)<br>            return sum / Double(readings.count)<br>        }<br>        do {<br>            let result = try await fetchTask.value<br>            print(&quot;Average temperature: \(result)&quot;)<br>        } catch {<br>            print(&quot;Failed to get data.&quot;)<br>        }<br>    }<br><br>// calling <br>      Task {<br>           await getAverageTemperature()<br>          }</pre><h3>How to cancel a Task</h3><p>In this example, the getAverageTemperature function fetches user data from a URL asynchronously using the URLSession. The await keyword is used to pause execution until the data is fetched, making the code appear synchronous while maintaining the benefits of asynchronicity.</p><p>Swift’s tasks use <em>cooperative cancellation</em>, which means that although we can tell a task to stop work, the task itself is free to completely ignore that instruction and carry on for as long as it wants. This is a feature rather than a bug: if cancelling a task made it stop work immediately, the task might leave your program in an inconsistent state.</p><p>There are seven things to know when working with task cancellation:</p><ol><li>You can explicitly cancel a task by calling its <strong>cancel()</strong> method.</li><li>Any task can check <strong>Task.isCancelled</strong> to determine whether the task has been cancelled or not.</li><li>You can call the <strong>Task.checkCancellation()</strong> method, which will throw a <strong>CancellationError</strong> if the task has been cancelled or do nothing otherwise.</li><li>Some parts of Foundation automatically check for task cancellation and will throw their own cancellation error even without your input.</li><li>If you’re using <strong>Task.sleep()</strong> to wait for some amount of time to pass, that will <em>not</em> honor cancellation requests – the task will still sleep even when cancelled.</li><li>If the task is part of a group and any part of the group throws an error, the other tasks will be cancelled and awaited.</li><li>If you have started a task using SwiftUI’s <strong>task()</strong> modifier, that task will automatically be canceled when the view disappears.</li></ol><p>We can explore a few of these in code. First, here’s a function that uses a task to fetch some data from a URL, decodes it into an array, then returns the average:</p><pre>func getAverageTemperature() async {<br>        let fetchTask = Task { () -&gt; Double in<br>            let url = URL(string: &quot;https://hws.dev/readings.json&quot;)!<br>            let (data, _) = try await URLSession.shared.data(from: url)<br>            let readings = try JSONDecoder().decode([Double].self, from: data)<br>            let sum = readings.reduce(0, +)<br>            return sum / Double(readings.count)<br>        }<br><br>      fetchTask.cancel()<br><br>        do {<br>            let result = try await fetchTask.value<br>            print(&quot;Average temperature: \(result)&quot;)<br>        } catch {<br>            print(&quot;Failed to get data.&quot;)<br>        }<br>    }<br><br>// calling <br>      Task {<br>           await getAverageTemperature()<br>          }</pre><p>Now we have one implicit cancellation point with the <strong>data(from:)</strong> call, and an explicit one with the check on <strong>Task.isCancelled</strong>. If either one is triggered, the task will return 0 rather than throw an error.</p><p><strong>Tip:</strong> You can use both <strong>Task.checkCancellation()</strong> and <strong>Task.isCancelled</strong> from both synchronous and asynchronous functions. Remember, async functions can call synchronous functions freely, so checking for cancellation can be just as important to avoid doing unnecessary work.</p><p>Best Practices</p><ol><li>Use async only when necessary, as not all functions need to be asynchronous.</li><li>Group related asynchronous tasks using structured concurrency to ensure proper task management and cancellation.</li><li>Favor the async/await pattern over completion handlers or delegates, especially for complex asynchronous workflows.</li><li>Be mindful of potential performance impacts, such as overuse of concurrency leading to excessive context switching.</li></ol><p>Conclusion</p><p>The introduction of the async/await paradigm in Swift has revolutionized asynchronous programming, offering a more readable and intuitive approach to handling concurrency. By allowing developers to write asynchronous code that closely resembles synchronous code, Swift has taken a significant step toward simplifying the complexity of modern software development. As you continue to explore Swift&#39;s async/await, you&#39;ll likely find yourself writing more efficient, clean, and maintainable asynchronous code.</p><p>Thank you..! 😊✌️ Happy coding..!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a06c9ee4dd0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton vs Dependency Injection in iOS Swift]]></title>
            <link>https://medium.com/@ranga.c222/singleton-vs-dependency-injection-in-ios-swift-47a056a822f?source=rss-c4448436c321------2</link>
            <guid isPermaLink="false">https://medium.com/p/47a056a822f</guid>
            <category><![CDATA[dependency-inversion]]></category>
            <category><![CDATA[singleton-pattern]]></category>
            <category><![CDATA[solid-principles-in-swift]]></category>
            <category><![CDATA[singleton-design-pattern]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Ranga C]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 11:43:30 GMT</pubDate>
            <atom:updated>2023-07-24T11:43:30.335Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bg5I188k-eV7Cm-sSd-GqQ.png" /></figure><p>Introduction: When developing iOS applications in Swift, one critical decision developers face is how to manage the creation and lifecycle of objects efficiently. Two popular design patterns that address this concern are Singleton and Dependency Injection. In this article, we will delve into the concepts of Singleton and Dependency Injection, examine their advantages and disadvantages, and provide insights into choosing the most appropriate pattern for your iOS Swift projects.</p><p><strong>Singleton Pattern</strong>: The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. This pattern is achieved by defining a static property to hold the single instance of the class and a private initializer to prevent external instantiation.</p><p>Advantages of Singleton:</p><ul><li>Global Accessibility: A Singleton instance can be accessed from anywhere within the application, making it convenient for sharing resources and managing centralized data.</li><li>Lazy Initialization: Singleton instances are created only when accessed for the first time, saving memory and resources until they are actually needed.</li></ul><p>Disadvantages of Singleton:</p><ul><li>Tight Coupling: Overuse of Singleton can lead to tight coupling between classes, making it difficult to test and maintain the codebase.</li><li>Global State: Singleton introduces global state, which can lead to unintended side effects and make debugging complex.</li></ul><p><strong>Dependency Injection</strong>: Dependency Injection is a pattern where dependencies (objects or services) are provided to a class from the outside, rather than being created internally. This is accomplished by passing the dependencies as parameters to the class’s initializer or as properties that can be set from outside.</p><p>Advantages of Dependency Injection:</p><ul><li>Decoupling: By passing dependencies from outside, Dependency Injection promotes loose coupling between classes, making code more modular and easier to test.</li><li>Flexibility: Dependency Injection allows different implementations of dependencies to be easily swapped, enhancing code flexibility and maintainability.</li></ul><p>Disadvantages of Dependency Injection:</p><ul><li>Increased Boilerplate Code: Implementing Dependency Injection can lead to more code for passing dependencies around, potentially making the codebase verbose.</li><li>Complexity: In large projects, managing dependencies can become complex, requiring careful planning and organization.</li></ul><p>Choosing the Right Approach:</p><ol><li>Singleton is suitable when:</li></ol><ul><li>There is a genuine need for only one instance of a class throughout the application (e.g., managing app configuration, logging).</li><li>Global accessibility is essential for sharing common data across multiple components.</li></ul><p>2 . Dependency Injection is recommended when:</p><ul><li>There is a need to promote decoupling and testability in the application.</li><li>Different implementations of dependencies might be required (e.g., using mock objects during testing).</li><li>You want to avoid global state and reduce the risk of hidden dependencies.</li></ul><p>Best Practices:</p><ul><li>Use Singleton sparingly and only when it is genuinely necessary for global accessibility and resource management.</li><li>Embrace Dependency Injection to foster decoupling and flexibility in your codebase.</li><li>Consider using Dependency Injection frameworks like Swinject or DaggerSwift to simplify the management of dependencies.</li></ul><p>let’s add an example to illustrate the difference between using Singleton and Dependency Injection in iOS Swift.</p><p>Example Scenario: Suppose we are developing a weather app that fetches weather data from different APIs based on user preferences. The app consists of two classes: WeatherService to handle data retrieval and SettingsManager to manage user preferences.</p><p>Singleton Approach:</p><pre>class WeatherService {<br>    static let shared = WeatherService()<br>    private init() {}<br><br>    func fetchWeatherData() -&gt; WeatherData {<br>        // Implementation to fetch weather data from the selected API<br>        // ...<br>        return weatherData<br>    }<br>}<br><br>class SettingsManager {<br>    static let shared = SettingsManager()<br>    private init() {}<br><br>    var selectedAPI: WeatherAPI = .openWeather // Default API<br><br>    func updateSelectedAPI(api: WeatherAPI) {<br>        self.selectedAPI = api<br>    }<br>}</pre><p>In this example, both WeatherService and SettingsManager are implemented as Singletons. The WeatherService instance is globally accessible and used to fetch weather data. The SettingsManager is also a Singleton, allowing the user to update the selected API.</p><p>Usage of Singleton in the App:</p><pre>// Fetch weather data using Singleton<br>let weatherData = WeatherService.shared.fetchWeatherData()<br><br>// Update selected API using Singleton<br>SettingsManager.shared.updateSelectedAPI(api: .weatherAPIX)</pre><p>Dependency Injection Approach:</p><pre>class WeatherService {<br>    let apiClient: WeatherAPIClient<br><br>    init(apiClient: WeatherAPIClient) {<br>        self.apiClient = apiClient<br>    }<br><br>    func fetchWeatherData() -&gt; WeatherData {<br>        // Implementation to fetch weather data using the provided API client<br>        // ...<br>        return weatherData<br>    }<br>}<br><br>class SettingsManager {<br>    var selectedAPI: WeatherAPI = .openWeather // Default API<br><br>    func updateSelectedAPI(api: WeatherAPI) {<br>        self.selectedAPI = api<br>    }<br>}</pre><p>In this example, we use Dependency Injection to pass the WeatherAPIClient to the WeatherService. The WeatherService no longer holds a reference to a specific API client implementation, making it more flexible.</p><p>Usage of Dependency Injection in the App:</p><pre>// Create WeatherAPIClient based on user preference<br>let apiClient = createAPIClientFromPreference()<br><br>// Inject the WeatherAPIClient into WeatherService<br>let weatherService = WeatherService(apiClient: apiClient)<br><br>// Fetch weather data using Dependency Injection<br>let weatherData = weatherService.fetchWeatherData()<br><br>// Update selected API<br>let settingsManager = SettingsManager()<br>settingsManager.updateSelectedAPI(api: .weatherAPIX)</pre><p>In this example, the WeatherService now relies on the injected WeatherAPIClient, which can be created based on the user&#39;s preference (e.g., openWeather or weatherAPIX). The SettingsManager remains independent and does not follow the Singleton pattern.</p><p>Conclusion: The Singleton and Dependency Injection patterns offer different approaches for managing object creation and dependencies in iOS Swift applications. The Singleton pattern provides global accessibility but may lead to tight coupling and global state. In contrast, Dependency Injection promotes decoupling and flexibility, making it easier to test and maintain code. By carefully considering the specific requirements of your app, you can choose the most suitable approach to create a robust and efficient iOS Swift application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47a056a822f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilizing Presentation Styles for iPad and iPhone With Single Storyboard View Controller]]></title>
            <link>https://medium.com/@ranga.c222/utilizing-presentation-styles-for-ipad-and-iphone-with-single-storyboard-view-controller-875bb84caf12?source=rss-c4448436c321------2</link>
            <guid isPermaLink="false">https://medium.com/p/875bb84caf12</guid>
            <category><![CDATA[adaptive-layout]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ipad-presentation-style]]></category>
            <category><![CDATA[model-presentation-style]]></category>
            <category><![CDATA[present-view-controller]]></category>
            <dc:creator><![CDATA[Ranga C]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 06:00:21 GMT</pubDate>
            <atom:updated>2023-06-23T06:00:21.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAzJM9HrLPmWhjRQ3BsyOw.png" /></figure><p>Introduction: As developers, one of our primary goals is to create apps that seamlessly adapt to different devices and screen sizes. Apple provides us with powerful tools and frameworks to achieve this, including presentation styles in Swift. In this article, we will explore how to leverage presentation styles to use the same storyboard view controller for both iPad and iPhone, ensuring a consistent user experience across devices.</p><ol><li>Understanding Presentation Styles: In iOS development, a presentation style defines the way a view controller is presented on the screen. By utilizing presentation styles, we can control how our view controller appears and interacts with the user, tailoring the experience to the specific device.</li><li>Preparing the Storyboard: To begin, open your Xcode project and navigate to the storyboard containing the view controller you want to adapt for both iPad and iPhone. Ensure that the storyboard is properly configured for Auto Layout, allowing the UI elements to adjust dynamically based on the available screen space.</li><li>Identifying Device Type: To determine the device type at runtime, we can use the UIDevice class provided by iOS. By checking the userInterfaceIdiom property of the device, we can differentiate between iPad and iPhone.</li></ol><p>Here’s an example code snippet to identify the device type:</p><p>I’ve created one view controller in storyboard using Auto layouts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DklzEpDS3F57Qi026mpXWQ.png" /></figure><pre> @IBAction func buttonTapped(_ sender: UIButton) {<br>        let vc = self.storyboard?.instantiateViewController(withIdentifier: &quot;WelcomePopupVC&quot;) as! WelcomePopupVC<br>        if UIDevice.current.userInterfaceIdiom == .pad {<br>            vc.modalPresentationStyle = .formSheet<br>        }else{<br>            vc.modalPresentationStyle = .overFullScreen<br>        }<br>        if #available(iOS 13.0, *) {<br>            vc.isModalInPresentation = true<br>        }<br>        self.present(vc, animated: true, completion: nil)<br>        <br>    }</pre><ol><li>Presentation Style for iPad: On the iPad, we have more screen real estate available, allowing us to present our view controller in different ways. One common approach is to utilize a popover presentation style, which presents the view controller as a floating window within the app.</li></ol><pre>vc.modalPresentationStyle = .formSheet</pre><p>2. Presentation Style for iPhone: On the iPhone, where screen space is more limited, we can utilize a fullscreen or a page sheet presentation style to provide a focused and immersive experience.</p><p>To adapt the presentation style for iPhone, add the following code inside the iPhone-specific configuration block:</p><pre>vc.modalPresentationStyle = .overFullScreen</pre><ol><li>Presenting the View Controller: Once you have configured the presentation style based on the device type, you can present the view controller using the present(_:animated:completion:) method of your current view controller.swiftCopy code</li></ol><pre>present(viewController, animated: true, completion: nil)</pre><p>Make sure to call this method when the user interacts with a relevant UI element in your app.</p><p>Testing and Refining: To ensure that your presentation styles work correctly on both iPad and iPhone, thoroughly test your app on different devices and orientations using simulators or physical devices. Pay attention to the layout, behavior, and overall user experience to identify any issues or inconsistencies.</p><p>During the testing phase, consider edge cases and handle any specific scenarios that may arise on different devices. Make adjustments to your code and UI elements as necessary to provide a seamless and visually appealing experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAzJM9HrLPmWhjRQ3BsyOw.png" /></figure><p>Conclusion: By leveraging presentation styles in Swift, we can create a single storyboard view controller that adapts to both iPad and iPhone, providing a consistent user experience</p><p>Thanks for reading 😊✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=875bb84caf12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Swift Interview Questions — With Answers! — III]]></title>
            <link>https://medium.com/@ranga.c222/10-swift-interview-questions-with-answers-iii-102024596f10?source=rss-c4448436c321------2</link>
            <guid isPermaLink="false">https://medium.com/p/102024596f10</guid>
            <category><![CDATA[ios-interview]]></category>
            <category><![CDATA[swift-interview-questions]]></category>
            <category><![CDATA[ios-interview-question]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ranga C]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 06:52:25 GMT</pubDate>
            <atom:updated>2023-06-08T06:52:25.840Z</atom:updated>
            <content:encoded><![CDATA[<h3>10 Swift Interview Questions — With Answers! — III</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzEKsSPmFptRpwsI28Zg2Q.png" /></figure><h3>1. Do we have an extension in Objective — C?</h3><p>The answer is YES.</p><h3>2. Difference between a category and extension in objective C?</h3><p>A category can be declared for any class, even if you don’t have the original implementation source code.</p><p>A class extension bears some similarity to a category, but it can only be added to a class for which you have the source code at compile time (the class is compiled at the same time as the class extension).</p><p>Categories allow you to add methods outside of the main interface file. Whereas Extensions must be implemented in main Interface file. Which means we can safely conclude you cannot use extensions for extending Builtin classes or Classes for which you don’t have the source code, there you should use Categories. And to use extensions you need access to the source of the class you are extending.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/0*7r9e3wmKFsjd0gu-.png" /></figure><h3>3. Fallthrough keyword in swift?</h3><p>In Swift, switch statements don’t fall through the bottom of each case and into the next one. That is, the entire switch statement completes its execution as soon as the first matching case is completed.</p><p>In swift, <strong>fallthrough</strong> statement is used in switch case to execute case statements which is next to the matched case statements based on our requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*byPAq9MGRqWsqu0n.png" /></figure><p>“case 4” is also executed even though it doesn’t match the criteria</p><blockquote><em>The </em><em>fallthrough keyword does not check the case conditions for the </em><em>switch case that it causes execution to fall into. The </em><em>fallthrough keyword simply causes code execution to move directly to the statements inside the next case (or </em><em>default case) block, as in C’s standard </em><em>switch statement behavior.</em></blockquote><h3>4. How to make a method inside a protocol optional in swift?</h3><p>We can do it in two ways.</p><p>The pure — swift way should be like providing the default implementation using protocol extension.</p><p>The objective — C compatibility way is using the <strong>@objc</strong> and optional keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E9DA4DpHs4JnOxea.png" /></figure><p><strong><em>Important:</em></strong> Drawback of objc — compatibility way is that <strong>MyProtocolObjc in the above example became a class — only protocol</strong>. A struct cannot conform to this protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lUT-KGGoQ-5ECb7X.png" /></figure><p>Error: <strong>non-class type ‘SomeStruct’ cannot conform to class protocol ‘MyProtocolObjc’</strong></p><h3>5. Reverse a string without using “reversed()” in-built function</h3><p>If the interviewer asks you to write the code on a paper, just kill him on the spot🔫💣🔪. For me, it will be really difficult to write optimized code without xcode.</p><p>Last time, when this question was asked, this is what I thought of doing first.[ pen and paper method] .</p><pre>extension String {func reverse() -&gt; String {var tempString = “”for char in self {tempString = String(char) + tempString}return tempString}}</pre><p>I was able to cut — shot it to a one-liner using Playgrounds . You have this logic using<strong> Higher-order function “<em>Reduce</em>” on the string. 🔥🔥🔥🔥🔥</strong></p><pre>extension String {<br>func reverse() -&gt; String  { return self.reduce(&quot;&quot;){ &quot;\($1)&quot; + $0 } }<br>}</pre><h3>6. Explain the class hierarchy of UIButton.</h3><p>NSObject → UIResponder → UIView → UIControl → UIButton.</p><blockquote><em>UITextField, UITextView, UISlider, UIDatePicker, UIPageControl, UISegmentedControl, UIStepper, UISwitch etc are all inheriting from UIControl.</em></blockquote><h3>What are the roles and responsibilities of each superclass?</h3><p><a href="https://developer.apple.com/documentation/uikit/uiresponder"><strong>UIResponder</strong></a>: An abstract class responsible for responding to and handling events. A responder implements the <a href="https://developer.apple.com/documentation/uikit/uiresponder/1621142-touchesbegan">touchesBegan(_:with:)</a>, <a href="https://developer.apple.com/documentation/uikit/uiresponder/1621107-touchesmoved">touchesMoved(_:with:)</a>, first responder handling, keyboard, and input related events etc.</p><p><strong><em>UIView</em></strong>: An object that manages the content for a rectangular area on the screen.</p><p><strong><em>UIControl</em></strong>: It is the base class for controls.</p><ul><li>It handles the control state like enabled, disabled, focused, highlighted etc.</li><li>It handles events like touchDown, touchupInside, valueChanged, editing events for UITextField etc.</li><li>Adding target, removing the target, handling actions etc.</li></ul><h3>7. SuperClass of UIViewController?</h3><p>UIResponder → UIViewController</p><h3>8. SuperClass of UIWindow?</h3><p>UIView → UIWindow</p><h3>9. How many windows are there for an iOS app?</h3><p>An iOS app can only have one active key window at a time.</p><p><a href="https://developer.apple.com/library/archive/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/Introduction/Introduction.html#//apple_ref/doc/uid/TP40009503"><strong>Apple doc says</strong></a>: Every application has at least one window that displays the application’s user interface on a device’s main screen. If an external display is connected to the device, applications can create a second window to present content on that screen as well.</p><h3>10. Difference between Self and self in Swift?</h3><p>‘Self’ is only available in a protocol or as the result of a method in a class.</p><p>Reference: <a href="https://www.hackingwithswift.com/example-code/language/self-vs-self---whats-the-difference">Hacking with swift</a>.</p><p>When you’re writing protocols and protocol extensions, there’s a difference between Self (capital S) and self (lowercase S). When used with a capital S, Self refers to the type that conforms to the protocol, e.g. String or Int. When used with a lowercase S, self refers to the value inside that type, e.g. “hello” or 556.</p><p>NB: BinaryInteger is a protocol.</p><pre>extension BinaryInteger { func squared() -&gt; Self { return self * self }}</pre><h3>11. What is the difference between static vs class functions/variables in Swift classes?</h3><p>static and class both associate a method/property with a class, rather than an instance of a class. The difference is that subclasses can override class methods; they cannot override static methods. So, in a Class, static function keyword can be written like:</p><pre>final class someFunction()</pre><blockquote><em>So , static is internally final .</em></blockquote><blockquote><em>static methods are static dispatch means the compiler know which method will be executed at runtime as the static method can not be overridden while the class method can be a dynamic dispatch as subclass can override these.</em></blockquote><h3>12. Explain the final keyword or… How can we prevent overrides &amp; subclassing in a class?</h3><p>You can prevent a method, property, or subscript from being overridden by marking it as <em>final</em>. Do this by writing the final modifier before the method, property, or subscript’s introducer keyword (such as final var, final func, final class func, and final subscript).</p><p>You can mark an entire class as final by writing the final modifier before the class keyword in its class definition (final class). Any attempt to subclass a final class is reported as a compile-time error.</p><p>As mentioned earlier, you can also use static keyword which does the functionality of that of a final class.</p><p>Reference: <a href="https://stackoverflow.com/questions/29636633/static-vs-class-functions-variables-in-swift-classes/#answer-37770112">StackOverflow</a></p><h3>13. Explain atomicity in both Objective-C and swift?</h3><p>The default value in Objective — C: <strong>atomic</strong></p><p>The default value in Swift: <strong>non-atomic</strong></p><p>Defining a property as atomic will guarantee that a valid value will be returned. Declaring a property atomic makes the compiler generate additional code that prevents concurrent access to the property. This additional code locks a semaphore, then gets or sets the property, and then unlock the semaphore. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned — the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.</p><blockquote><em>Atomic properties suffer from minor performance hit due to locking and unlocking before and after setting/getting a value.</em></blockquote><p>Non-atomic properties have no guarantee regarding the returned value. It can be the correct value, a partially written value or even some garbage value.</p><p>There is no atomic/non-atomic keyword in Swift. we should use locks/semaphore etc to make a property atomic when multiple threads try to access the same value.</p><blockquote><em>Atomicity property attributes (atomic and nonatomic) are not reflected in the corresponding Swift property declaration, but the atomicity guarantees of the Objective-C implementation still hold when the imported property is accessed from Swift.</em></blockquote><h3>14. What is a Singleton pattern? How to create one in swift?</h3><p>A Singleton can only have one instance for the lifetime of the application it exists in. Singletons exist to give us singular global state. Such examples are NSNotificationCenter, UIApplication, and NSUserDefaults.</p><pre>final class Singleton {static let sharedInstance = Singleton() private init() {} // init should be private}</pre><p>Any variable declared with the <strong>let</strong> keyword is a <strong>constant</strong> and, therefore, read-only and <strong>thread</strong>-<strong>safe.</strong></p><p>Static keyword makes sure it is lazily initialized inside a dispatch_once block. Static is internally final by default.</p><blockquote><a href="https://developer.apple.com/documentation/dispatch/1447169-dispatch_once"><em>dispatch_once</em></a><em>: Executes a block object once and only once for the lifetime of an application.</em></blockquote><p>Making the init method as private so that nobody can access the init() method directly and create a new instance of the Singleton class.</p><h3>15. Can enums have stored properties?</h3><p>Enums can have methods, subscripts, and computed properties. But it cannot have stored properties.</p><h3>16. Can you install an iOS app on a real device without a paid developer account?</h3><p>YES, you can. But, without enrolling in the Apple Developer Program, your app will only last for 7 days on your device. After that, you’ll have to re-deploy it to your device via Xcode. If you’re enrolled in the Apple Developer Program, you won’t have this inconvenience.</p><h3>17. Can we make a let as weak</h3><p>No, ‘weak’ must be a mutable variable, because it may change at runtime. When we declare something as weak, it becomes an optional. It may or may not have a value. It will be mutated [set to nil] once there is no reference to it.</p><pre>class SomeClass { }class SomeOtherClass {weak let someClassObj: SomeClass? = nil <br>// error: &#39;weak&#39; must be a mutable variable, because it may change at runtime}</pre><h3>18. Can we make a let as unowned</h3><p>Yes. unowned references will always have a value. It is not an optional.</p><blockquote><em>Note: UNOWNED references can be a let or a var.</em></blockquote><h3>19. Is it possible to create segues between different storyboards within the same project?</h3><p>Yes. Using <a href="https://medium.com/@abhimuralidharan/how-to-create-segues-between-different-storyboards-in-the-same-xcode-project-ios-d3a9c8fc221">storyboard references</a>.</p><h3>20. What is Optional Chaining?</h3><p><em>Optional chaining</em> is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.</p><h3>21. Bounds vs nativeBounds?</h3><p><strong><em>nativeBounds</em></strong><em>: </em>This rectangle is based on the device in a portrait-up orientation. This value does not change as the device rotates.</p><p><strong><em>bounds</em></strong>: This rectangle is specified in the current coordinate space, which takes into account any interface rotations in effect for the device. Therefore, the value of this property may change when the device rotates between portrait and landscape orientations.</p><p>Enjoy!!. I will be adding more questions in this article. Just follow me so that you don’t miss any of them.</p><h4>Where to go previous — <a href="https://medium.com/@ranga.c222/10-swift-interview-questions-with-answers-ii-1296f557ef8e">part 2</a></h4><p><strong>Thanks for reading!</strong> I hope this would be useful for understand or refreshing some of the iOS concept. Please share your feedback, queries regarding any of the topic in comments below. ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=102024596f10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift : Passing Data Between View Controllers]]></title>
            <link>https://medium.com/@ranga.c222/swift-passing-data-between-view-controllers-868b9d177111?source=rss-c4448436c321------2</link>
            <guid isPermaLink="false">https://medium.com/p/868b9d177111</guid>
            <category><![CDATA[notification-center]]></category>
            <category><![CDATA[callback]]></category>
            <category><![CDATA[delegation]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[data-passing-swift]]></category>
            <dc:creator><![CDATA[Ranga C]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 07:41:11 GMT</pubDate>
            <atom:updated>2023-06-01T07:41:11.797Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift : Passing Data Between View Controllers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uFJ0wInji1F07kqzTnjNYw.png" /></figure><p>In Swift, there are several ways to pass data between view controllers. Here are a few commonly used methods:</p><ol><li><strong>Using Segues:</strong></li></ol><ul><li>Define a property in the destination view controller to hold the data you want to pass.</li><li>Override the prepare(for:sender:) method in the source view controller.</li><li>Set the data property in the destination view controller inside the prepare(for:sender:) method.</li><li>Example:</li></ul><pre>// SourceViewController.swift<br>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {<br>    if segue.identifier == &quot;YourSegueIdentifier&quot; {<br>        if let destinationVC = segue.destination as? DestinationViewController {<br>            destinationVC.dataProperty = dataToPass<br>        }<br>    }<br>}</pre><p><strong>2. Using a Closure/Callback:</strong></p><ul><li>Define a closure property in the destination view controller to hold the callback.</li><li>Set the closure property in the destination view controller.</li><li>Call the closure from the source view controller and pass the data.</li><li>Example:</li></ul><pre>// DestinationViewController.swift<br>var callback: ((String) -&gt; Void)?<br><br>// SourceViewController.swift<br>if let destinationVC = storyboard?.instantiateViewController(withIdentifier: &quot;DestinationViewController&quot;) as? DestinationViewController {<br>    destinationVC.callback = { data in<br>        // Handle the passed data<br>    }<br>    navigationController?.pushViewController(destinationVC, animated: true)<br>}</pre><p><strong>3. Using a Delegate:</strong></p><ul><li>Define a protocol that declares the necessary methods to pass the data.</li><li>Create a delegate property in the destination view controller and set it to the source view controller.</li><li>Implement the protocol methods in the source view controller.</li><li>Call the delegate methods from the destination view controller and pass the data.</li><li>Example:</li></ul><pre><br>// DestinationViewController.swift<br>protocol DataDelegate: AnyObject {<br>    func sendData(data: String)<br>}<br><br>class DestinationViewController: UIViewController {<br>    weak var delegate: DataDelegate?<br>    <br>    // Call the delegate method when you want to pass the data<br>    delegate?.sendData(data: dataToPass)<br>}<br>// SourceViewController.swift<br>class SourceViewController: UIViewController, DataDelegate {<br>    // Implement the delegate method to receive the data<br>    func sendData(data: String) {<br>        // Handle the passed data<br>    }<br>    if let destinationVC = storyboard?.instantiateViewController(withIdentifier: &quot;DestinationViewController&quot;) as? DestinationViewController {<br>        destinationVC.delegate = self<br>        navigationController?.pushViewController(destinationVC, animated: true)<br>    }<br>}</pre><p>These are just a few examples of how you can pass data between view controllers in Swift. The appropriate method to use depends on your specific use case and application architecture.</p><p><strong>4.Instance/Direct Method</strong></p><p>you can achieve that by accessing the view controller instance directly. Here’s an example.</p><pre>// SourceViewController.swift<br>if let destinationVC = storyboard?.instantiateViewController(withIdentifier: &quot;DestinationViewController&quot;) as? DestinationViewController {<br>    destinationVC.dataProperty = dataToPass<br>    navigationController?.pushViewController(destinationVC, animated: true)<br>}</pre><p>In this example, we assume that both the source view controller (SourceViewController) and the destination view controller (DestinationViewController) are embedded in a UINavigationController.</p><p>By instantiating the destination view controller using instantiateViewController(withIdentifier:), you can access its properties directly and assign the desired data to a property (dataProperty in this case).</p><p>Keep in mind that using direct method may tightly couple the two view controllers, which can make your code less modular and harder to maintain. It’s generally recommended to use more structured approaches like segues, closures, or delegates for passing data between view controllers.</p><h3>NotificationCenter</h3><p>Another method for passing data between view controllers is by using NotificationCenter. This involves creating a notification in the sending view controller and observing it in the receiving view controller.</p><p>The sending view controller then posts the notification, which triggers the observer method in the receiving view controller.</p><p>Here’s an example:</p><pre>// In the sending view controller<br>let notificationName = Notification.Name(&quot;PassDataNotification&quot;)<br>NotificationCenter.default.post(name: notificationName, object: nil, userInfo: [&quot;data&quot;: &quot;Hello, World!&quot;])<br>// In the receiving view controller<br>override func viewDidLoad() {<br>    super.viewDidLoad()<br>    NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: notificationName, object: nil)<br>}<br>@objc func handleNotification(_ notification: Notification) {<br>    if let data = notification.userInfo?[&quot;data&quot;] as? String {<br>        print(data) // Output: &quot;Hello, World!&quot;<br>    }<br>}</pre><h3>Conclusion</h3><p>Passing data between view controllers is a common task in iOS app development, and there are several ways to accomplish it.</p><p>Segues with prepare(for:sender:), delegation, and NotificationCenter are all effective methods depending on the specific use case and preferences of the developer.</p><p>Each method has its own advantages and disadvantages, so it’s important to choose the one that best fits your app’s needs.</p><p>I hope this explanation has been helpful to you in understanding how to pass data between view controllers in iOS using different methods. If you have any further questions, feel free to ask!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=868b9d177111" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>