<?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 Soham Bhattacharjee on Medium]]></title>
        <description><![CDATA[Stories by Soham Bhattacharjee on Medium]]></description>
        <link>https://medium.com/@sohamb.1390?source=rss-8a1bd9b4a616------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*v9fNW7t1_6t3-nMabbSk7g.jpeg</url>
            <title>Stories by Soham Bhattacharjee on Medium</title>
            <link>https://medium.com/@sohamb.1390?source=rss-8a1bd9b4a616------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 02:45:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sohamb.1390/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[ Task {} in Swift — “The Async Chameleon of Modern Concurrency”]]></title>
            <link>https://medium.com/@sohamb.1390/task-in-swift-the-async-chameleon-of-modern-concurrency-2aa14e15add0?source=rss-8a1bd9b4a616------2</link>
            <guid isPermaLink="false">https://medium.com/p/2aa14e15add0</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[tasks]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <dc:creator><![CDATA[Soham Bhattacharjee]]></dc:creator>
            <pubDate>Mon, 05 May 2025 20:10:54 GMT</pubDate>
            <atom:updated>2025-05-05T20:27:52.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧵 <strong>Task {} in Swift — “The Async Chameleon of Modern Concurrency”</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hn9m-qDIiZZTKw9E" /><figcaption>Photo by <a href="https://unsplash.com/@find_something_pretty_everyday?utm_source=medium&amp;utm_medium=referral">Hasmik Ghazaryan Olson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>🔍 Why This Matters</h3><p>Swift’s Task {} is more than just a block of async code — it&#39;s a shape-shifting, thread-agnostic powerhouse that adapts to your app’s concurrency needs without you having to worry about queues, threads, or locking. Much like a 🦎 that changes colour based on its environment, Task {} molds itself to:</p><ul><li>The <strong>priority</strong> you assign.</li><li>The <strong>actor</strong> context it’s launched from.</li><li>Whether you’re calling it from <strong>sync</strong> or <strong>async</strong> code.</li></ul><p>With Task {}, you&#39;re not asking <em>which thread</em> your code runs on — you&#39;re trusting Swift to run it <em>when and where it makes the most sense</em>. It&#39;s safe, structured, and incredibly elegant.</p><blockquote>The Task {} syntax was introduced in Swift <strong>5.5 as part of Swift’s Structured Concurrency</strong>, which was officially released in <strong>September 2021</strong> alongside <strong>Xcode 13 </strong>and <strong>iOS 15</strong>.</blockquote><h3>🧠 <strong>Demystifying Task: What Really Happens Under the Hood?</strong></h3><p>Whenever you declare a Task {}, you&#39;re creating a new asynchronous <em>unit of work</em> (a single task), which may itself run asynchronously and <em>spawn other tasks </em>or<em> await multiple operations </em>within it.</p><p>When a Task {} is declared, it’s internally scheduled on a <strong>cooperative thread pool, </strong>not on a dedicated thread (GCD).</p><h4>🔧 What is a Cooperative Thread Pool?</h4><p>Swift Concurrency uses a <strong>global cooperative thread pool</strong> to run asynchronous tasks. Unlike GCD where you push blocks onto dispatch queues that map to threads, Swift’s concurrency runtime is more <strong>task-oriented</strong>, not thread-oriented.</p><h4>🚦 Why “Cooperative”?</h4><p>Because tasks:</p><ul><li><strong>Do not hog threads</strong> — they <em>cooperate</em> by yielding control when suspended (e.g., on await)</li><li>Share a <strong>small number of threads</strong> efficiently across many tasks</li><li>Rely on the <strong>runtime</strong> to suspend and resume them based on system availability and resource contention.</li></ul><p>Now, let’s see how we declare a Task:</p><pre>Task {<br>    await fetchImage()<br>}</pre><p>As you can see, Task takes a closure in which we place the code to be executed asynchronously. However, it&#39;s important to understand that we cannot control the thread on which the Task will run. A Task {} always inherits its parent&#39;s context, meaning it runs on the same thread that triggered it. In the example above, it’s impossible to determine which thread the Task {} will run on unless you know the caller. Let’s dive deeper into this.</p><pre>class ImageViewController: UIViewController {<br>    func viewDidLoad() {<br>       super.viewDidLoad()<br>       fetchImage()<br>    }<br><br>    func fetchImage() {<br>        Task {<br>            do {<br>                let (data, _) = try await URLSession.shared.data(from: URL(string: &quot;https://api.flickr.com/services/rest?text=Animal&amp;method=flickr.photos.search&amp;api_key={PLACE_YOUR_OWN_KEY}&amp;format=json&amp;safe_search=1&amp;extras=url_t&amp;nojsoncallback=1&quot;)!)<br>                print(data.count)<br>            } catch {<br>                print(error.localizedDescription)<br>            }<br>        }<br>   }<br>}</pre><p>I’ve extended the code a bit in the above example. Now, I’ve placed the method inside a ViewController, and in fetchImage(), I’m fetching a Flickr image, with the caller being viewDidLoad(). If you run this code snippet, you’ll notice that the Task {} inside fetchImage() runs on the main thread. If you set a breakpoint and check the stack trace, you’ll observe something similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWJgL_zZaB3lPrtmeA0hgw.png" /></figure><p><strong>The first question that might come to mind is: <em>‘Isn’t </em></strong><strong><em>Task supposed to run on a concurrent thread?&#39;</em></strong><br>The answer is <strong>no</strong>. As mentioned earlier, you cannot control which thread a Task will run on — it always inherits its parent’s context. In this example, that&#39;s the main thread, because we know that UIViewController methods like viewDidLoad() are invoked on the @MainActor. (I&#39;ll cover Global Actors in a separate post.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*WTNOAmnCp56Y6-vGk_pEvg.png" /></figure><p>Now, let’s try to check when does the Task use a concurrent thread.</p><pre>class ImageViewModel {<br>    func fetchImage() {<br>        Task {<br>            do {<br>                let (data, _) = try await URLSession.shared.data(from: URL(string: &quot;https://api.flickr.com/services/rest?text=Animal&amp;method=flickr.photos.search&amp;api_key={PLACE_YOUR_OWN_KEY}&amp;format=json&amp;safe_search=1&amp;extras=url_t&amp;nojsoncallback=1&quot;)!)<br>                print(data.count)<br>            } catch {<br>                print(error.localizedDescription)<br>            }<br>        }<br>   }<br>}<br><br>class ImageViewController: UIViewController {<br>    let vm: ImageViewModel = ImageViewModel()<br><br>    func viewDidLoad() {<br>       super.viewDidLoad()<br>       vm.fetchImage()<br>    }<br>}</pre><p>I made a small tweak to the existing code snippet. I’ve now moved the fetchImage() method into a ViewModel called ImageViewModel, and I&#39;m calling this method from the ViewController using an instance of ImageViewModel. This change worked like a magic!</p><p>As soon as fetchImage() is invoked, I observed that Task {} is running in a concurrent thread!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30mzhcMp075WT0euVTfPEQ.png" /></figure><p>Why did this happen? The answer is quite simple: when I moved fetchImage() to a ViewModel (which is not annotated with @MainActor), the Swift Concurrency runtime inherited the parent context&#39;s thread — which, in this case, is a background (concurrent) thread. If the method you call from a MainActor context, is <strong>not annotated with </strong><strong>@MainActor</strong>, it means Swift does not enforce that the method <strong>must run on the main thread</strong>.</p><h3>🔄 <strong>Context Switching in Task</strong></h3><p>Whenever we invoke an asynchronous operation inside a Task {} using the await keyword, it creates a suspension point. At this point, Swift Concurrency doesn&#39;t block the current thread while waiting for the result — instead, it releases the thread so it can be used elsewhere. When the awaited operation completes, the global cooperative thread pool automatically assigns a thread to resume execution. So, it’s not guaranteed that the task will resume on the same thread from which it was initiated.</p><h3>🧩 Few points to be remembered</h3><ul><li>Swift’s Task {} is a <em>job</em> or <em>unit of work</em>, not a GCD thread or a block on a queue.</li><li>It runs on a <strong>global cooperative thread pool</strong>.</li><li>Tasks <strong>cooperate</strong> by suspending on await and resuming later, freeing threads in between.</li><li>This allows <strong>scaling thousands of concurrent tasks</strong> with a limited number of threads.</li><li>Tasks don’t explicitly inherit the thread they’re launched from. What they <strong>do inherit</strong> is the <strong>actor context</strong>, and that may <em>imply</em> a certain thread (e.g., @MainActor implies main thread).</li><li>Similarly, it can inherit the task priority from its caller, unless you define one:<br><em>Task(priority: .background) { … }</em></li><li>If you launch a Task from a background thread and your function has no actor annotation (e.g., @MainActor), Swift may continue execution on a background thread, depending on the current context.</li><li>This is a <strong>runtime optimization</strong> — Swift avoids switching to the main thread unless explicitly told to.</li><li>Threads are reused efficiently — tasks get scheduled, paused, and resumed without owning a specific thread.</li></ul><p>I will talk about <strong><em>Task.detached{}</em>,</strong> <strong><em>TaskGroup{}</em></strong><em> </em>&amp;<em> </em><strong><em>TaskCancellation</em></strong><em> </em>in another blog post. Stay Tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2aa14e15add0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design an Analytics Manager in iOS]]></title>
            <link>https://medium.com/@sohamb.1390/design-an-analytics-manager-in-ios-0430d58304cf?source=rss-8a1bd9b4a616------2</link>
            <guid isPermaLink="false">https://medium.com/p/0430d58304cf</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[analytics-manager]]></category>
            <dc:creator><![CDATA[Soham Bhattacharjee]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 11:17:04 GMT</pubDate>
            <atom:updated>2025-01-28T04:40:36.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G7f3t41YnCEXwTZI" /><figcaption>Photo by <a href="https://unsplash.com/@dosejuice?utm_source=medium&amp;utm_medium=referral">Dose Juice</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In many System Design interviews, candidates often face this question how to design a scalable Analytics Manager which can accommodate any 3rd party Analytics SDK and, can track events from any screens of the app.</p><h3>Idea</h3><p>If we are asked to build a system design, we should always start from gathering the requirements followed by thinking of approaches which would make the system scalable. In our case, the analytics manager should be agnostic to any analytics libraries, the basic functionality should not be impacted if we have to add new analytics libraries in future. From a high level, it should have a <em>func track(_ event: Event) </em>which would capture the corresponding event. The underlying complexity to track the events in all the analytics server should not be visible outside of the analytics manager.</p><h3>HLD</h3><p>If we have to make an HLD of a generic Analytics Manager, it should be like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j4ZF7Du07QdERgpSq4VFwg.png" /><figcaption>Analytics Manager HLD</figcaption></figure><p>Since the Analytics Manager has to be decoupled from any other components and it has to be testable, we must follow POP (Protocol Oriented Programming). Now, Let’s understand What are these components depicted on this HLD.</p><h4>AnalyticsService</h4><p>It’s a simple protocol which has few properties and methods. Now if we want to add any Analytics Service, we must conform it by <em>AnalyticsService</em>. For an instance, we have a <strong><em>FirebaseService</em></strong> which has conformed to <em>AnalyticsService, </em>and as a result, it has to define all the required methods and properties. Likewise, if we want to have another analytics service e.g <strong><em>MixPanel, </em></strong>we again have to conform to <em>AnalyticsService. </em>This way, each and every analytics service has it’s own flavour of implementations, thus we are following <strong>Separation of Concern.</strong></p><h4>AnalyticsManager</h4><p>It’s a gateway of using the Analytics services. Since there will be only one instance of the analytics manager throughout the lifecycle of the application, we can declare it as a Singleton. It has a property called <strong>“services” </strong>which is nothing but an array of all analytics services. The idea behind having this property is to hit all the analytics services in one shot whenever the <em>“track(_ event: Event)” </em>method is invoked. This manager class has all the helper methods which are required to send the events to the respective analytics server.</p><h4>Event</h4><p>This is nothing but a struct of an event instance. Here, an event has a name and it’s corresponding properties, e.g. let’s say we want to send a login type event to the server whenever the user logs into the app; we can initialise the <strong>Event </strong>like this:</p><pre>let event = Event(name: &quot;Login_Type&quot;, properties: [&quot;loginType&quot;: &quot;SSO&quot;])</pre><h4>AnalyticsType</h4><p>This is an enum of each individual analytics service type. It can be useful when a specific set of events needs to be sent to a particular analytics service, rather than all of them.</p><p>Now that we know what each component signifies in the HLD, we can jump into the implementation to design the Analytics Manager. Here, I have written just a boilerplate code to make things simplified. In actual implementation, we may have to add few more methods or properties based on the requirement.</p><pre>struct Event {<br>    let name: String<br>    let properties: [String: Any]<br>}</pre><pre>enum AnalyticsType: Equatable {<br>    case mixPanel<br>    case firebase<br>    case adobeAnalytics<br>}</pre><pre>struct FirebaseAnalyticsService: AnalyticsService {<br>    func trackEvent(_ event: Event) {<br>        // Track Event<br>    }<br><br>    func unsetEvent(_ event: Event) {<br>        // Unset Event<br>    }<br>    <br>    func initialize(application: UIApplication, launchOptions: [UIApplication.LaunchOptionsKey : Any]?) {<br>        // Initialise Firebase<br>    }<br>    <br>    var analyticsType: AnalyticsType {<br>        .firebase<br>    }<br>}</pre><pre>struct MixAnalyticsService: AnalyticsService {<br>    func trackEvent(_ event: Event) {<br>        // Track Event<br>    }<br><br>    func unsetEvent(_ event: Event) {<br>        // Unset Event<br>    }<br>    <br>    func initialize(application: UIApplication, launchOptions: [UIApplication.LaunchOptionsKey : Any]?) {<br>        // Initialise Firebase<br>    }<br>    <br>    var analyticsType: AnalyticsType {<br>        .mixPanel<br>    }<br>}</pre><pre>final class AnalyticsManager {<br>    static let manager: AnalyticsManager = AnalyticsManager()<br>    <br>    private var services: [AnalyticsService] = []<br><br>    private init() {<br>        // Setup all SDKs<br>        services = [FirebaseAnalyticsService(), HeapAnalyticsService()]<br>    }<br>    <br>    func initialize(application: UIApplication, launchOptions: [UIApplication.LaunchOptionsKey : Any]?) {<br>        for service in services {<br>            service.initialize(application: application, launchOptions: launchOptions)<br>        }<br>    }<br>    <br>    func trackEvent(_ event: Event) {<br>        for service in services {<br>            service.trackEvent(event)<br>        }<br>    }<br>    <br>    func track(_ events: [Event], for analyticsType: AnalyticsType) {<br>        if let service = services.first(where: { $0.analyticsType == analyticsType }) {<br>            for event in events {<br>                service.trackEvent(event)<br>            }<br>        }<br>    }<br>    <br>    func unsetEvent(_ event: Event) {<br>        for service in services {<br>            service.unsetEvent(event)<br>        }<br>    }<br>}</pre><p>Now that we have implemented all the components of the system, it’s time to initialise the AnalyticsManager and to use them in the app. In AppDelegate.swift, we can initialise the manager like this:</p><pre>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br>    // Override point for customization after application launch.<br>    AnalyticsManager.manager.initialize(application: application, launchOptions: launchOptions)<br>    return true<br>}</pre><p>To use our AnalyticsManager, we just have to call the “track(_ event: Event)” method like this:</p><pre>func onTapLogin(_ loginType: LoginType) {<br>   // Login Code<br>  <br>  // Track Login type in Firebase<br>  AnalyticsManager.manager.track([Event(name: &quot;Login_Type&quot;, properties: [&quot;loginType&quot;: loginType.rawValue])], for: .firebase)<br>  AnalyticsManager.manager.track([Event(name: &quot;Login_Mode&quot;, properties: [&quot;loginType&quot;: loginType.rawValue])], for: .mixPanel)<br>}</pre><p>That’s all!! I hope you find this blog useful and to-the-point!</p><p>You can find the gist here</p><p><a href="https://gist.github.com/sohamb1390/0a012581423c24376f746eb6318987b4">https://gist.github.com/sohamb1390/0a012581423c24376f746eb6318987b4</a></p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0430d58304cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design of an elevator in Swift (Part I)]]></title>
            <link>https://medium.com/@sohamb.1390/system-design-of-an-elevator-in-swift-part-i-f0f5cfab9d32?source=rss-8a1bd9b4a616------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0f5cfab9d32</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Soham Bhattacharjee]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 10:42:13 GMT</pubDate>
            <atom:updated>2024-12-30T10:42:13.570Z</atom:updated>
            <content:encoded><![CDATA[<p>In many technical interviews, the most crucial round is the system design round, where the discussion focuses on building a system in the most optimized and robust way.</p><p>The <strong>elevator design</strong> question is not new, and most tier-1 organizations include it in their system design rounds. Let us focus on designing an elevator system for a specific apartment.</p><h4>What are the initial considerations when designing an elevator system?</h4><ol><li>The building has <em>n </em>number of elevators.</li><li>The building has <em>m </em>number of floors.</li><li>There can be at most 3 states of an elevator: <strong>movingUp</strong>, <strong>movingDown</strong> or <strong>idle</strong>.</li><li>A request for an elevator can originate from any floor or from inside the elevator.</li><li>A request for an elevator can originate while the elevator is already moving upward or downward, or when the elevator is in an idle state.</li></ol><h4>Data structures to be used to design an elevator system</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwp4nCyYKB1olhw73Rtr7Q.png" /></figure><ol><li>Request to get an elevator at any floor follows <strong>FCFS (first-come-first-serve) </strong>pattern.In the FCFS algorithm, requests are served in the order they are added to the queue. This means the elevator will first go to the passenger on floor 2 and take them to their destination. Next, it will proceed to floor 4 to pick up the passenger and take them to their destination, followed by floor 3, and so on. We need to keep track of all the floor requests in two <a href="https://www.geeksforgeeks.org/queue-data-structure/"><strong>queues</strong></a>: <strong><em>one queue to store all floors above the current floor</em></strong> and <strong><em>another to store all floors below it</em></strong>.</li><li><strong>Current State</strong>: we need to keep track of the current state of each elevator. This could be either <strong>movingUp, </strong>or <strong>movingDown </strong>or <strong>idle.</strong></li><li><strong>Current Floor: </strong>We need to keep track of the current floor for various reasons, one of which is to determine whether the next requested floor is in the same direction. e.g, if an upward request comes from the 5th floor while the elevator is currently on the 2nd floor, the elevator system will evaluate this request and decide whether to stop at the 5th floor. In this case, it will stop.</li><li><strong>Destinaton List: </strong>An array of all the destination floors is required for the elevator system to identify which floors it needs to stop at.</li></ol><h4>Desigining the Elevator System in code:</h4><pre>enum ElevatorState: String {<br>    case movingUp<br>    case movingDown<br>    case idle<br>        <br>    var displayValue: String {<br>        switch self {<br>        case .movingUp:<br>             return &quot;Moving Up&quot;<br>        case .movingDown:<br>             return &quot;Moving Down&quot;<br>        case .idle:<br>             return &quot;Idle&quot;<br>        }<br>    }<br>}<br><br>final class Elevator {<br>  // MARK: Properties<br><br>  /// Elevator&#39;s unique ID<br>  let id: String<br>  /// The current floor of the elevator residing at<br>  private (set) var currentFloor: Int = 0<br>  /// The current state of the Elevator<br>  private (set) var currentState: ElevatorState = .idle<br>  /// An array containing all the destination floors<br>  private (set) var destinationList: [Int] = []<br>  <br>  // MARK: - Constructor<br>  init(id: String, currentFloor: Int = 0, currentState: ElevatorState = .idle, destinationList: [Int] = []) {<br>      self.id = id<br>      self.currentFloor = currentFloor<br>      self.currentState = currentState<br>      self.destinationList = destinationList<br>   }<br><br>  // MARK: - Elevator Request<br>  /// This method adds the request floor number to the destination list array and sort it based on the comparison between the current floor and the requested floor.<br>  /// This method also assigns the exact state of the elevator based on the comparison between the current floor and the requested floor.<br>  func assignRequest(for floor: Int) {<br>    // Append the floor to the destination list<br>    destinationList.append(floor)<br><br>    // e.g if the request floor is 5 and the current floor is 2, the state of the elevator should be &quot;movingUp&quot;.<br>    if floor &gt; currentFloor {<br>       currentState = .movingUp<br>       // Sort the destinationList in descending order since the lift is moving upward.<br>       destinationList = destinationList.sorted(by: { $0 &lt; $1 }<br>    // e.g if the request floor is 1 and the current floor is 3, the state of the elevator should be &quot;movingDown&quot;.<br>    } else if floor &lt; currentFloor {<br>       // Sort the destinationList in ascending order since the lift is moving downward.<br>       destinationList = destinationList.sorted(by: { $0 &gt;$1 }<br>       currentState = .movingDown<br>    }<br>  }<br><br>  /// This method should be called when the elevator has started moving.<br>  /// It maintains the current floor calculation along with destinationList manipulation.<br>  /// Whenever the elevator calls this method, it immediately checks for the requested elevator direction.<br>  /// if it&#39;s upward, the current floor should be increased by 1 at each floor.<br>  /// Likewise, the current floor should be reduced by 1 eat each floor if the direction is downward.<br>  func move() {<br>    // If there are not destination floors, the elevator should be in &quot;idle&quot; state.<br>    guard !destinationList.isEmpty else {<br>        currentState = .idle<br>        return<br>    }<br>  <br>    // Let&#39;s adjust the current floor based on the elevator&#39;s state.<br>    if currentState == .movingUp {<br>       currentFloor += 1<br>    } else if currentState == .movingDown {<br>       currentFloor -= 1<br>    }<br>    <br>    // Whenever the elevator reaches to a destination floor, that floor has to be removed from the destination list to make the list accurate.<br>    if let index = destinationList.firstIndex(of: currentFloor) {<br>       destinationList.remove(at: index)<br><br>       // We also have to check whether the list has now become empty or not. If yes, the elevator should be in idle state.<br>       if destinationList.isEmpty {<br>          currentState = .idle<br>       }<br>    }<br>  }<br>}</pre><h4>Explaination</h4><p>As we can see from the above code snippet, we have created a class named <em>“Elevator” </em>which predominantly deals with three things:</p><ol><li>The current state of the Elevator.</li><li>The current floor.</li><li>The destination floors list.</li></ol><p>Each <em>“Elevator” </em>instance has the capability of taking request by invoking</p><pre>func assignRequest(for floor: Int) {}</pre><p>This method is essentially responsible for changing the state, appending the incoming floor to the destination list and sorting it based on the direction. If some person sends a request from the 5th floor when the elevator is moving up from 2nd to 3rd, the destination list should be sorted in the descending order so that it can stop at 5th floor. Likewise, the destination list will be sorted in ascending order if the lift is moving down.</p><p>On the other hand, most of the heavy lifting job of the total elevator ecosystem is dependant upon:</p><pre>func move() {}</pre><p>This method is responsible for the updating the current floor and the destination list accurately whenever the elevator is moving up/down or reaches to it’s destination floor. Based on the current state of the elevator, the current floor is calculated. Whenever the elevator reaches to any floor, the floor number is removed from the destination list to keep it accurate, we also have to check whether the list has become empty or not at the end; if it’s empty, the state of the elevator should become “idle”.</p><p>We will talk about how to use this <em>Elevator</em> class in the real world in the next part of this BLOG.</p><p>Thanks for reading!</p><p>Cheers!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0f5cfab9d32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature flag and it’s success story]]></title>
            <link>https://medium.com/@sohamb.1390/feature-flag-and-its-success-story-91fe81a6a791?source=rss-8a1bd9b4a616------2</link>
            <guid isPermaLink="false">https://medium.com/p/91fe81a6a791</guid>
            <category><![CDATA[feature-flags]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Soham Bhattacharjee]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 08:20:09 GMT</pubDate>
            <atom:updated>2023-12-02T04:27:31.606Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArcI2vkIZAP1oSj_EE-7UQ@2x.jpeg" /><figcaption>Photo by Jigar Panchal on Unsplash</figcaption></figure><p>As an iOS App Engineer, you may have realized some features are only meant to be publicly available once they’re completed, or sometimes, you want to avoid your particular feature being included for a specific release cycle due to many external factors.</p><p>Let’s consider our QA engineers have successfully tested a feature you developed for the next upcoming release. Now, just a week before releasing the app, we came under the impression that the corresponding server team encountered a showstopper on the UAT server, and due to this, they won’t be able to support this feature from an API perspective. They will roll back the recent deployments until the critical bug is fixed.</p><p>Unlike the server team, we cannot roll back our changes and jump back to the earlier flavor of the app so quickly. Even if we do, we will have to spend a lot of time doing regression, as it will be a time and resource-intensive task, and we cannot afford it just before the release.</p><blockquote>What do we need to eliminate this error-prone job so our release can go smoothly with other features/bug fixes?</blockquote><blockquote><strong>We can hold off accessing a particular feature using a Feature Flag</strong></blockquote><h3>What is Feature Flag?</h3><p>Feature Flag is nothing but a concept in software development where a feature can be enabled/disabled without modifying the underlying source code.</p><h3><strong>How can we implement a feature flag in iOS?</strong></h3><p>There are multiple ways available to develop a feature flag. Today, I will describe one of the ways I chose for my everyday work.</p><pre>struct AppFeature {<br>  /// An enum which declares all the features that you want to put under a feature flag<br>  enum FeatureFlag {<br>    case purchaseScreen<br>    case billingScreen<br>    case reBrandingWork<br><br>    /// An enum which declares all the development statuses that indicate which state your feature currently resides at.<br>    fileprivate enum DevelopmentStatus {<br>      /// This indicates your feature is currently being developed<br>      case underDevelopment<br>      /// This indicates your feature is good to go for release<br>      case releaseReady<br>      /// This indicates your feature has currently gone for a toss.<br>      case shelved<br>    }<br><br>    /// An enum which is used to return the current development status for each module<br>    fileprivate var FeatureStatus: DevelopmentStatus {<br>      switch self {<br>        case purchaseScreen:<br>          return underDevelopment<br>        case billingScreen:<br>          return releaseReady<br>        case reBrandingWork:<br>          return shelved<br>      }<br>    }<br>  }<br><br>  /// This static method returns a boolean value stating whether a feature is release ready or not.<br>  /// - Parameter feature: An object of `FeatureFlag` for which we have to evaluate whether the feature is release ready.<br>  static func isAvailable(_ feature: FeatureFlag) -&gt; Bool {<br>    return feature.FeatureStatus == .releaseReady<br>  }<br>}</pre><p>Here, we have declared a <em>struct </em>named AppFeature , which holds all the features of your app that you want to be part of the feature flag concept.</p><p>This enum also contains another <em>enum</em> named DevelopmentStatus, which tells us what all the development phases any feature can go into. In this example, we have 3 phases i.e. underDevelopment , releaseReady , shelved . The definition of each phase is described in the code snippet itself.</p><p>Let’s talk about a computed property namedFeatureStatus which is also declared in this enum. The objective of this property is to return the current development status of a particular feature.</p><blockquote>Now, you will ask how can we consume this feature flag?</blockquote><p>Ideally, we must have some places in our code from where we can enable/disable a particular feature. We will safeguard that place by our Feature Flag implementation. Let’s say, the feature you built is not going to be released soon, and you want to keep it under the feature flag.</p><p>You can do it by invoking the method below from the place that triggers your ongoing feature flow. Before that, in the FeatureStatus enum, you must mark your feature as underDevelopment. Hence, it will return false once you pass your feature type to this method as an argument. Doing this will block the user from seeing the feature on the production app.</p><pre>static func isAvailable(_ feature: FeatureFlag) -&gt; Bool {<br>    return feature.FeatureStatus == .releaseReady<br>}</pre><p>Tada!! You are now safe to ship your app even if one of your features is being developed and the underlying codebase still contains it.</p><blockquote>Implementing feature flags can help you avoid keeping a large amount of code separate on a different feature branch for an extended period. This can ultimately reduce the likelihood of encountering unknown errors during the process of merging it back to the development branch. If merge conflicts are not resolved correctly, some of your code may be overlooked.</blockquote><p>Thank you for reading!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91fe81a6a791" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unknown side of Parameterized protocol in iOS 15]]></title>
            <link>https://medium.com/@sohamb.1390/unknown-side-of-parameterized-protocol-in-ios-15-9816e43770eb?source=rss-8a1bd9b4a616------2</link>
            <guid isPermaLink="false">https://medium.com/p/9816e43770eb</guid>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[parameterized-protocol]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[opaque-types]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Soham Bhattacharjee]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 18:28:44 GMT</pubDate>
            <atom:updated>2023-12-02T04:27:57.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNqq2aBj6HQharavG-5XVA@2x.jpeg" /><figcaption>Photo by Archcookie on Unsplash</figcaption></figure><p>I hope everyone is having a chilly winter; I wanted to share some experience in debugging &amp; fixing one weird issue with you all.</p><p>So, one day, I got to know from one of the QA engineers that the application was not getting installed on one of the devices (iPhone SE 2nd Gen), which has iOS 15.6.1, but surprisingly, it’s working on a higher version of iOS (&gt;15).</p><p>We needed to learn what was going on with the build. Luckily, I have a device with iOS 15.6.1 and ran the affected branch on it through Xcode. Again, to my surprise, I successfully ran the app on the device. Then I tried installing the app by creating an IPA, and we were shocked! The build was crashing at the launch itself.</p><p>We then tried to look at the crash log, but unfortunately, we couldn’t find anything on it. From this point, we tried multiple things, such as:</p><ul><li>Downgraded the <strong>swift-tools-version</strong> of a couple of newly built in-house framework packages to 5.5 from 5.7</li><li>Updated the minimum deployment version to iOS 15 on each framework that we consume through SPM</li><li>Set the value of Always Embed Swift Standard Libraries as <strong>true.</strong></li></ul><p>And many more workarounds that we got from StackOverflow.</p><p>Finally, we decided to remove the two new libraries that we built recently one by one. This decision was made because we learned from the QA team that the build is working correctly on the device without those frameworks.</p><p>For now, let’s consider the names of those frameworks as <strong>“FrameworkAlpha” </strong>and <strong>“FrameworkBeta”</strong>.</p><p>At first, we removed <strong>FrameworkAlpha</strong> and kept <strong>FrameworkBeta</strong> as is.</p><p><strong>Tada</strong>!! The build was correctly installed without any launch time crash, which means there’s some issue in the <strong>FrameworkAlpha</strong>.</p><p>It took a lot of work to determine the root cause of a runtime crash. But, we were determined to solve this issue as it was a showstopper issue.</p><p>From this point, we removed the class files of that framework one by one, kept creating IPA files, and checked on my device to see whether it was crashing. This process went in loop until <strong>we encountered a bizarre scenario.</strong></p><p>In one of the class files of <strong>FrameworkAlpha</strong>, we declared an optional property of type <strong>parameterized generic protocol</strong> like this:</p><pre>public var somevariable: (any SomeGenericProtocol&lt;T&gt;)? = nil</pre><p>and the definition of the protocol was:</p><pre>public protocol SomeGenericProtocol&lt;SomePreDeclaredType&gt; {<br>    associatedtype SomePreDeclaredType<br>    <br>    var someVariable: SomeEnumType { get }<br>    <br>    func someFunction(type: SomePreDeclaredType, someEnumType: SomeEnumType) -&gt; String<br>}</pre><p>This looks neat and clean and works like a charm if you run it on a device through Xcode. :D :D</p><p><strong>However, this protocol definition has an issue. Apple doesn’t have runtime support for any </strong><strong>Parameterized Protocol on iOS 15 and lower versions. Sometimes, the compiler throws a compiler error like this:</strong></p><blockquote><strong>Runtime support for parameterized protocol types is only available in ios 16.0.0 or newer</strong></blockquote><p>Since there is no runtime support for this parameterized protocol on iOS 15, it crashed at launch time. Interestingly, this code was crashing only on a debug/release build through IPA, not through Xcode. I was amazed by the nature of this crash!!! Unfortunately, there’s a glitch in the compiler, and it doesn’t always throw this error. I was pretty lucky to get this error after building the project 4–5 times without cleaning.</p><blockquote><strong>I didn’t find any straightforward blog/solution for this issue. But what I found to fix this issue is minor and consists of no risk.</strong></blockquote><p>I updated the protocol declaration like this:</p><pre>public protocol SomeGenericProtocol&lt;SomePreDeclaredType&gt;: AnyObject {<br>    associatedtype SomePreDeclaredType<br>    <br>    var someVariable: SomeEnumType { get }<br>    <br>    func someFunction(type: SomePreDeclaredType, someEnumType: SomeEnumType) -&gt; String<br>}</pre><p>So, conforming this protocol to AnyObject did the trick.</p><p>If anyone is facing this kind of a weird runtime crash, just take a look at your parameterized protocol (if you have) :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9816e43770eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[@autoclosure in Swift]]></title>
            <link>https://medium.com/@sohamb.1390/autoclosure-in-swift-e0c30d6cf17c?source=rss-8a1bd9b4a616------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0c30d6cf17c</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[autoclosure]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Soham Bhattacharjee]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 07:02:02 GMT</pubDate>
            <atom:updated>2023-12-02T04:28:30.202Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2iBHn7Ioahp_R8rsgFlEXA@2x.jpeg" /><figcaption>Photo by BoliviaInteligente on Unsplash</figcaption></figure><p>As we develop mobile applications, we know how it’s important to improve it’s performance at any cost in order to provide a better user experience. As part of this effort, we do a lot of memory optimizations. One of them is @autoclosure.</p><p>Let’s say, you are going to perform a CPU intensive operation in a particular method and the outcome of this method will be passed on to another method in order to evaluate the result. However, in the second method we also have boolean parameter, which decides whether we really need to evaluate that expensive opretaion’s result or not.</p><p>Neverthless, whenever we call the second method, we always have to invoke the first method before in order to send the result to the second one, even though the first argument is false. As a result, memory optimisation has gone for a toss if the first argument is false 😞.</p><p>Never mind! we have @autoclosure which can rescue us in this situation.</p><h3>What is @autoclosure?</h3><p>In Swift, @autoclosure keyword automatically wraps an argument of a method into a closure to delay the execution of the code inside the closure. In the above scenario, if we use it, it can prevent calling the CPU-intensive method if it’s not required. Let’s see this in action below.</p><pre>func sendGoodMorningGreetings(_ goodMorning: Bool, to whom: @autoclosure () -&gt; String) {<br>    // If goodMorning argument is true, only then, we have to print the name of the sender.<br>    if goodMorning {<br>        print(whom())<br>    }<br>}<br><br>func someCPUIntensiveTask() -&gt; String {<br>    // Let&#39;s say we are accessing the contact book of the device to filter out all the <br>    // contacts who have profile pictures, and who have organisation title in their contact poster.<br>    // This operation indeed takes some amount of memory. Finally, it will give an array of String. For simplicity purpose,<br>    // we are returning a single String value for now.<br>    &quot;Anish&quot;<br>}<br><br>// In this case, `someCPUIntensiveTask()` method won&#39;t get called<br>sendGoodMorningGreetings(false, to: someCPUIntensiveTask())<br>// In this case, `someCPUIntensiveTask()` will get called<br>sendGoodMorningGreetings(true, to: &quot;Rohit&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0c30d6cf17c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>