<?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 Aayushi: iOS Developer on Medium]]></title>
        <description><![CDATA[Stories by Aayushi: iOS Developer on Medium]]></description>
        <link>https://medium.com/@aayushi9555?source=rss-2736a3f91944------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WfnDNKUexeXcyDs9.jpg</url>
            <title>Stories by Aayushi: iOS Developer on Medium</title>
            <link>https://medium.com/@aayushi9555?source=rss-2736a3f91944------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:03:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aayushi9555/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[SwiftUI Interview Questions: Beginner level]]></title>
            <link>https://medium.com/@aayushi9555/swiftui-interview-questions-beginner-level-521f25597f59?source=rss-2736a3f91944------2</link>
            <guid isPermaLink="false">https://medium.com/p/521f25597f59</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Aayushi: iOS Developer]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 07:48:17 GMT</pubDate>
            <atom:updated>2026-03-02T07:48:17.598Z</atom:updated>
            <content:encoded><![CDATA[<p>Below are some commonly asked SwiftUI beginner questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpverIkKUiUXF-MB7BSRVg.png" /></figure><h3>1. What is the difference between UIKit and SwiftUI?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lvrncs7efPqkJmFMwwXgEw.png" /></figure><h3>2. What does Declarative UI really mean?</h3><p>Declarative means you describe the desired result, not the steps to achieve it.</p><p>Example:</p><pre>struct LoginView: View {<br>    @State private var isLoggedIn = false<br>    var body: some View {<br>            Group {<br>                if isLoggedIn {<br>                    Text(&quot;Welcome&quot;)<br>                } else {<br>                    Button(&quot;Login&quot;) {<br>                        isLoggedIn = true<br>                    }<br>                }<br>            }<br>        }<br>    }</pre><p>You are not:</p><ul><li>Removing subviews</li><li>Adding subviews</li><li>Calling reload methods</li></ul><p>You describe what the UI should look like for a given state.</p><p>The system computes the rest.</p><h3>3. What are the different types of state in SwiftUI?</h3><h3>@State</h3><ul><li>Local to the view.</li><li>Used for simple, view-owned data.</li><li>Triggers view updates when mutated.</li></ul><h3>@Binding</h3><ul><li>A reference to state owned elsewhere.</li><li>Enables two-way communication.</li><li>Does not own storage.</li></ul><h3>@ObservedObject</h3><ul><li>Used with ObservableObject.</li><li>The view observes changes.</li><li>The object is created and owned externally.</li></ul><h3>@StateObject</h3><ul><li>Also used with ObservableObject.</li><li>The view creates and owns the object.</li><li>Prevents reinitialisation during view refreshes.</li></ul><p>Rule of thumb:</p><ul><li>If the view creates it → @StateObject</li><li>If the view receives it → @ObservedObject</li></ul><h3>@EnvironmentObject</h3><ul><li>Shared observable object provided through the environment.</li><li>Avoids passing dependencies manually across multiple levels.</li><li>Must be injected before access.</li></ul><h3>4. Why are SwiftUI Views Structs?</h3><ul><li>They are lightweight descriptions of UI.</li><li>They can be recreated frequently.</li><li>State is stored separately using property wrappers.</li><li>Value semantics reduce unintended side effects.</li></ul><p>SwiftUI views are not UI containers.<br> They are declarations of UI.</p><h3>5. What triggers a SwiftUI view update?</h3><p>A view refresh happens when:</p><ul><li>A @State value changes.</li><li>A published property inside an observed object changes.</li><li>A binding value changes.</li><li>An environment value changes.</li></ul><p>SwiftUI then recalculates body and determines what needs updating.</p><h3>6. What is the difference between @ObservedObject and @StateObject?</h3><p>Both are used with classes that conform to ObservableObject.</p><h3>@StateObject</h3><ul><li>The view creates and owns the object.</li><li>SwiftUI keeps the instance stable for the lifetime of that view.</li><li>The object is initialised only once per view lifecycle.</li></ul><p>Use when:</p><ul><li>The view is responsible for creating the observable object.</li></ul><h3>@ObservedObject</h3><ul><li>The object is created outside the view.</li><li>The view subscribes to changes.</li><li>The view does not manage the object’s lifecycle.</li></ul><p>Use when:</p><ul><li>The object is injected into the view from a parent or dependency container.</li></ul><h3>7. Why can using @ObservedObject instead of @StateObject sometimes cause unexpected behavior?</h3><p>Because SwiftUI views are structs and can be recreated frequently.</p><p>If you create an observable object inside a view like this:</p><pre>struct ExampleView: View {<br>    @ObservedObject var viewModel = ExampleViewModel()<br>}</pre><p>The view may be recreated during state updates.<br> Since @ObservedObject does not preserve initialisation, the object can be reinitialised, leading to:</p><ul><li>Reset state</li><li>Lost data</li><li>Re-triggered network calls</li><li>Unexpected UI behaviour</li></ul><p>Using @StateObject in this case ensures the instance is created only once and survives view refreshes.</p><p>Hope this article made your Swift journey a bit smoother. Next set of SwiftUI questions will be covered in the next part.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=521f25597f59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mediator + Integrator Patterns in iOS Swift: Module Communication Without Imports]]></title>
            <link>https://medium.com/@aayushi9555/mediator-integrator-patterns-in-ios-swift-module-communication-without-imports-908c39c878d3?source=rss-2736a3f91944------2</link>
            <guid isPermaLink="false">https://medium.com/p/908c39c878d3</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Aayushi: iOS Developer]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 16:41:45 GMT</pubDate>
            <atom:updated>2026-01-16T16:41:45.308Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VHLlJLV97enL-YHJ4LqHrw.png" /></figure><p>Modern iOS apps rarely stay “single-module” for long. When you have multiple modules in your project there is a common rule:</p><blockquote><strong><em>One framework should not import another</em></strong><em>, but features still need to communicate.</em></blockquote><p>Disadvantages ifframeworks directly import each other:</p><ul><li>circular dependencies</li><li>tight coupling</li><li>difficulty in testing</li></ul><p>A clean and scalable solution for this problem is using <strong>Mediator + Integrator</strong>.</p><h3>Mediator Pattern</h3><p>A <strong>Mediator</strong> is a central component that routes communication between modules <strong>without them knowing about each other</strong>.Modules don’t call other modules.<br> They call the mediator.<br>Think of <strong>Mediator = traffic police</strong>.</p><h3>Integrator (Composition Root)</h3><p>An <strong>Integrator</strong> is the layer that wires everything together:</p><ul><li>connects modules to the mediator</li><li>injects dependencies</li><li>decides the real app flow</li></ul><p>Think of <strong>Integrator = city planner who builds roads + assigns traffic police</strong>.</p><h3>Simple Example using the modules Auth &amp; Profile</h3><h3>Modules (each is a separate framework)</h3><ul><li><strong>AuthKit</strong> → handles login</li><li><strong>ProfileKit</strong> → checks if profile is complete</li><li><strong>AppShell</strong> → integrates everything (main app target)</li></ul><h3>Requirement</h3><ul><li>AuthKit must NOT import ProfileKit</li><li>ProfileKit must NOT import AuthKit</li><li>Still, after login, ProfileKit should decide what happens next</li></ul><h3>The Wrong Way (Tight Coupling)</h3><pre>AuthKit  ---&gt; imports ---&gt; ProfileKit</pre><p>This creates dependency pressure and often leads to circular imports later.</p><h3>Diagram 2: The Right Way (Mediator + Integrator)</h3><pre>AuthKit  ---&gt;  AppMediator  &lt;---  ProfileKit<br>                  ^<br>                  |<br>           AppIntegrator wires both</pre><p>AuthKit and ProfileKit stay independent.</p><h3>Step 1: Shared Contract (Only thing both modules import)</h3><p>Create a tiny shared package/framework: <strong>CoreContracts</strong><br> This is the ONLY shared dependency.</p><pre>public enum AppEvent {<br>    case loginSuccess(userId: String)<br>}<br>public enum AppRoute {<br>    case showHome<br>    case showProfileSetup(userId: String)<br>}</pre><h3>Step 2: Mediator Protocol</h3><pre>public protocol AppMediating: AnyObject {<br>    func publish(_ event: AppEvent)<br>    func navigate(_ route: AppRoute)<br>}</pre><ul><li>publish = tell the system “something happened”</li><li>navigate = request the app to move to the next screen</li></ul><h3>Step 3: AuthKit Only Publishes Login Success</h3><p>AuthKit does NOT decide navigation.<br> It just emits an event.</p><pre>// inside AuthKit<br>mediator.publish(.loginSuccess(userId: &quot;U123&quot;))</pre><p>That’s AuthKit’s entire job.</p><h3>Step 4: ProfileKit Listens and Decides Next Step</h3><p>ProfileKit receives the event and decides what should happen.</p><ul><li>if profile is complete → go Home</li><li>else → go to Profile Setup</li></ul><pre>// inside ProfileKit<br>func onEvent(_ event: AppEvent) {<br>    switch event {<br>    case .loginSuccess(let userId):<br>        let isComplete = false // pretend we checked locally/API<br>        if isComplete {<br>                    mediator.navigate(.showHome)<br>                } else {<br>                    mediator.navigate(.showProfileSetup(userId: userId))<br>                }<br>            }<br>        }</pre><p>ProfileKit still does NOT import AuthKit.</p><h3>Step 5: Integrator Wires Everything Together (AppShell)</h3><p>The <strong>Integrator</strong> is where your app connects modules.</p><ul><li>creates mediator</li><li>connects AuthKit + ProfileKit</li><li>performs navigation</li></ul><p><strong>This is the only layer allowed to know everything.</strong></p><pre>// inside AppShell (main app target)<br>let mediator = AppMediator()<br><br>let auth = AuthFeature(mediator: mediator)<br>let profile = ProfileFeature(mediator: mediator)<br>mediator.onEvent = { event in<br>    profile.onEvent(event)<br>}<br>mediator.onRoute = { route in<br>    // AppShell does actual navigation here<br>}</pre><p>Event Flow</p><pre>User logs in<br>   |<br>AuthKit publishes: loginSuccess(userId)<br>   |<br>AppMediator forwards event<br>   |<br>ProfileKit decides route:<br>  - showHome OR showProfileSetup<br>   |<br>AppShell navigates</pre><h3>Advantages of using this pattern</h3><h4><strong>1) No direct framework imports</strong></h4><p>AuthKit and ProfileKit only depend on CoreContracts.</p><h4>2) Modules stay focused</h4><ul><li>AuthKit = authentication only</li><li>ProfileKit = profile rules only</li></ul><h4>3) AppShell controls the product flow</h4><p>If laterthe requirement changes:<br> “After login, show consent screen before profile check”</p><p>You update only AppShell wiring.<br> AuthKit and ProfileKit stay untouched.</p><h3>Key Takeaway</h3><p>If you want modular iOS frameworks where modules <strong>must not import each other </strong>but still need to collaborate.</p><p>Use <strong>Mediator</strong> to communicate and <strong>Integrator</strong> to wire dependencies</p><p>It keeps your codebase clean, scalable, and testable.</p><p>Hope this article made your Swift journey a bit smoother. Until next time — happy Swifting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=908c39c878d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interview Question: How to make a singleton class thread safe in Swift]]></title>
            <link>https://medium.com/@aayushi9555/interview-question-how-to-make-a-singleton-class-thread-safe-in-swift-b6ea6f22be4d?source=rss-2736a3f91944------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6ea6f22be4d</guid>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[singleton-pattern]]></category>
            <dc:creator><![CDATA[Aayushi: iOS Developer]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 12:02:27 GMT</pubDate>
            <atom:updated>2025-11-08T12:02:27.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IXlOI67pLp23_mlN" /></figure><p>A simple singleton counter that is not thread safe:</p><pre>class Counter {<br>    static let shared = Counter()<br>    private init() {}<br>    private var value = 0<br>    func increment() {<br>        value += 1<br>    }<br>    func getValue() -&gt; Int {<br>        return value<br>    }<br>}</pre><p>At first, this looks fine. You can access Counter.shared.increment() from anywhere in your app. But if two threads call increment() at the same time, both might read the same old value and write it back after adding one. One increment will be lost. This is a <strong>race condition</strong>.</p><p>Even reading value while another thread is writing to it can return inconsistent data. So we must make the counter thread safe.</p><h3>Where to make it thread safe</h3><p>If only one thread updates the counter and others only read it later, then protecting writes is enough. But if both reading and writing happen together from multiple threads, both should be protected.</p><h3>1: Using NSLock</h3><p>A simple and effective method is to use <strong>NSLock</strong>. You lock before reading or writing so that only one thread accesses the value at a time.</p><pre>class CounterLock {<br>    static let shared = CounterLock()<br>    private init() {}<br>    private var value = 0<br>    private let lock = NSLock()<br><br>    func increment() {<br>        lock.lock()<br>        value += 1<br>        lock.unlock()<br>    }<br><br>    func getValue() -&gt; Int {<br>        lock.lock()<br>        let current = value<br>        lock.unlock()<br>        return current<br>    }<br>}</pre><p>This guarantees that only one thread can read or modify the counter at a time. Use this when your operations are short and fast. Avoid holding a lock while doing long tasks such as file or network operations.</p><h3>2: Using DispatchSemaphore</h3><p>A semaphore acts like a gate that only lets a fixed number of threads enter. To make our counter safe, we allow only one thread at a time.</p><pre>class CounterSemaphore {<br>    static let shared = CounterSemaphore()<br>    private init() {}<br>    private var value = 0<br>    private let semaphore = DispatchSemaphore(value: 1)<br><br>    func increment() {<br>        semaphore.wait()<br>        value += 1<br>        semaphore.signal()<br>    }<br><br>    func getValue() -&gt; Int {<br>        semaphore.wait()<br>        let current = value<br>        semaphore.signal()<br>        return current<br>    }<br>}</pre><p>This works similar to NSLock. The semaphore waits before entering and signals after leaving. It is slightly more flexible since you can allow multiple threads if you want, but here we use one for full safety.</p><h3>3: Using a Serial Dispatch Queue</h3><p>Another simple way is to send all reads and writes to a serial queue. The queue ensures only one operation runs at a time.</p><pre>class CounterSerialQueue {<br>    static let shared = CounterSerialQueue()<br>    private init() {}<br>    private var value = 0<br>    private let queue = DispatchQueue(label: &quot;com.example.counter&quot;)<br><br>    func increment() {<br>        queue.sync {<br>            value += 1<br>        }<br>    }<br><br>    func getValue() -&gt; Int {<br>        var current = 0<br>        queue.sync {<br>            current = value<br>        }<br>        return current<br>    }<br>}</pre><p>Here every read and write goes through the same queue. It is clean and safe, and you do not have to handle locking manually. This is a good choice for most small shared resources.</p><h3>4: Using a Concurrent Queue with Barrier</h3><p>When your code reads often but writes occasionally, you can use a concurrent queue. Multiple reads can happen together, but writes must be exclusive. A barrier block ensures that writes happen safely without overlapping with reads.</p><pre>class CounterBarrier {<br>    static let shared = CounterBarrier()<br>    private init() {}<br><br>    private var value = 0<br>    private let queue = DispatchQueue(label: &quot;com.example.counter&quot;, attributes: .concurrent)<br>    <br>    func increment() {<br>        queue.async(flags: .barrier) {<br>            self.value += 1<br>        }<br>    }<br><br>    func getValue(completion: @escaping (Int) -&gt; Void) {<br>        queue.async {<br>            completion(self.value)<br>        }<br>    }<br>}</pre><p>In this setup, many reads can run in parallel, improving performance. But when a write comes in, it waits for all reads to finish, updates the value, and then allows new reads again. This is perfect for cases where you have frequent reads and rare writes.</p><h3>5: Using Swift Concurrency and Actors</h3><p>With modern Swift, actors give you the easiest and safest thread safety. An actor protects its data automatically so you do not need locks or queues.</p><pre>actor CounterActor {<br>    static let shared = CounterActor()<br>    private init() {}<br><br>    private var value = 0<br><br>    func increment() {<br>        value += 1<br>    }<br><br>    func getValue() -&gt; Int {<br>        return value<br>    }<br>}</pre><p>Usage:</p><pre>Task {<br>    await CounterActor.shared.increment()<br>    let result = await CounterActor.shared.getValue()<br>    print(result)<br>}</pre><p>Actors ensure that only one task interacts with their state at a time, giving you full safety without manual synchronisation.</p><h3>Which part should be thread safe — read, write or both?</h3><p>If your counter is read frequently and written occasionally, protect only the writes and allow reads concurrently. This pattern is often called <em>read concurrent, write exclusive</em>, as shown in the barrier example.</p><p>If both reads and writes can happen at any time from different threads, you must protect both using locks or serial queues.</p><p>If the writes are done first and then only reads happen after, you may not need any synchronisation at all.</p><h3>Summary and recommendations</h3><ul><li>For small and quick code, <strong>NSLock</strong> or <strong>semaphore</strong> works well.</li><li>For clean structure, use a <strong>serial queue</strong>.</li><li>For frequent reads and few writes, use a <strong>concurrent queue with barrier</strong>.</li><li>For new Swift code, <strong>prefer actors</strong>.</li></ul><p>Always protect writes. Protect reads only when they can overlap with writes. Keep critical sections small and never hold locks during long operations.</p><p>This simple singleton counter example shows all the main ways to make your shared data thread safe. Hope this article made your Swift journey &amp; interview preparation a bit smoother. Until next time — happy Swifting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6ea6f22be4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Interview Questions Beyond the Basics]]></title>
            <link>https://medium.com/@aayushi9555/swift-interview-questions-beyond-the-basics-76fbefd6e428?source=rss-2736a3f91944------2</link>
            <guid isPermaLink="false">https://medium.com/p/76fbefd6e428</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Aayushi: iOS Developer]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 11:40:51 GMT</pubDate>
            <atom:updated>2025-11-08T11:40:51.266Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve been actively preparing for iOS interviews, you already know the common Swift questions — differences between classes and structs, memory management, ARC, and so on. In this post, we’ll go beyond those basics and cover deeper follow-up questions that interviewers often use to test your real understanding of Swift’s internals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8XRppYRL4IVQJapz" /></figure><h3>1. Difference Between Class, Struct, and Actor</h3><p>You might already know the standard differences:</p><ul><li><strong>Classes</strong>: Reference type, support inheritance, deinitializers, and identity comparison.</li><li><strong>Structs</strong>: Value type, copied on assignment, no inheritance.</li></ul><p>But interviewers may follow up with: <strong>“What’s the difference between a class, a struct, and an actor?”</strong></p><h3>Key Difference</h3><p>Actors are reference types like classes but with <strong>built-in thread safety</strong>. Swift ensures that mutable state inside an actor is only accessed from one task at a time.</p><pre>actor Counter {<br>  private var value = 0<br>  <br>  func increment() {<br>  value += 1<br>  }<br>  <br>  func getValue() -&gt; Int { value }<br>}<br><br><br>let counter = Counter()<br>Task {<br>  await counter.increment()<br>  print(await counter.getValue())<br>}</pre><p>Unlike a regular class, you cannot access value directly from outside the actor—it enforces isolation. This prevents data races automatically.</p><h3>2. Is an Actor Always Thread Safe?</h3><p>Not always.</p><p>Actors guarantee safety <strong>for their own isolated state</strong>, but if you inject dependencies from outside that are not actor-isolated, thread safety can still be broken.</p><pre>actor DataHandler {<br>  var externalCache: Cache? // injected from outside<br>  <br>  <br>  func store(key: String, value: String) {<br>    externalCache?.save(key: key, value: value) // ❌ Not thread-safe if Cache isn&#39;t safe<br>  }<br>}</pre><p>Here, DataHandler itself is actor-isolated, but externalCache might be accessed from multiple threads. So thread safety depends on what’s being accessed.</p><h3>3. ARC and Retain Cycles</h3><p><strong>Question:</strong> What is it called when one class holds a strong reference to another class, and the other also holds a strong reference back?</p><p><strong>Answer:</strong> A <em>retain cycle</em>.</p><pre>class Teacher {<br>    var student: Student?<br>}<br><br>class Student {<br>    var teacher: Teacher?<br>}</pre><p>Both objects keep each other alive. The fix: use weak or unowned.</p><pre>class Student {<br>    weak var teacher: Teacher?<br>}</pre><h3>When to Use weak vs unowned</h3><ul><li><strong>weak</strong> → When the reference can become nil.</li><li><strong>unowned</strong> → When the reference should never become nil (like delegate patterns).</li></ul><pre>UIView.animate(withDuration: 0.3) { [unowned self] in<br>    self.view.alpha = 0<br>}</pre><blockquote><strong><em>Note:</em></strong><em> Although we used </em><em>unowned here, in closures like </em><em>UIView.animate or </em><em>DispatchQueue.main.async, you generally don’t need </em><em>[weak self] or </em><em>[unowned self] because the closure doesn’t outlive the object—it’s executed and released quickly. Using it here is safe but not required.</em></blockquote><h3>4. Can Swift Classes Have Multiple Inheritance?</h3><p>No, Swift does <strong>not</strong> support multiple inheritance for classes.</p><p>However, Swift allows conforming to <strong>multiple protocols</strong>, which can achieve similar behavior through composition.</p><pre>protocol Flyable { func fly() }<br>protocol Swimmable { func swim() }<br>class Duck: Flyable, Swimmable {<br>    func fly() { print(&quot;Flying&quot;) }<br>    func swim() { print(&quot;Swimming&quot;) }<br>}</pre><h3>5. Dynamic vs Static Dispatch in Protocols</h3><p><strong>Question:</strong> Are protocol methods dynamically or statically dispatched?</p><p><strong>Answer:</strong></p><ul><li>Methods defined <strong>in the protocol itself</strong> → dynamically dispatched.</li><li>Methods provided via <strong>protocol extension</strong> → statically dispatched.</li></ul><pre>protocol Speaker { func speak() }<br>extension Speaker {<br>    func speak() { print(&quot;Hello from extension!&quot;) }<br>}<br>struct Human: Speaker {<br>    func speak() { print(&quot;Hello from struct!&quot;) }<br>}<br>let h: Speaker = Human()<br>h.speak() // Prints &quot;Hello from extension!&quot; (static dispatch)</pre><h3>6. The @frozen Keyword</h3><p>Introduced with Swift 5.0, @frozen ensures that a type’s cases will <strong>never change</strong> in the future.</p><p>It’s mainly used for enums to allow the compiler to safely omit the default case in switch statements.</p><pre>@frozen enum Status {<br>    case success<br>    case failure<br>}<br><br>func handle(_ status: Status) {<br>    switch status {<br>    case .success: print(&quot;Success&quot;)<br>    case .failure: print(&quot;Failure&quot;)<br>    }<br>}</pre><p>The compiler knows that Status will not gain more cases in the future, so you don’t need a default.</p><h3>7. Singleton and Completion Handling</h3><p><strong>Question:</strong> You are given this singleton and asked how to ensure the completion block is called only once.</p><pre>class NetworkManager {<br>    static let shared = NetworkManager()<br>    private init() {}<br><br>    func loadData(from urlString: String, completion: @escaping (Data?) -&gt; Void) {<br>        guard let url = URL(string: urlString) else {<br>            completion(nil)<br>            return<br>        }<br>        let task = URLSession.shared.dataTask(with: url) { data, _, error in<br>            var result: Data? = nil<br>            // completion will be called exactly once from this defer block<br>            defer { completion(result) }<br>            if let error = error {<br>                print(&quot;Network error: \(error.localizedDescription)&quot;)<br>                // result remains nil, so defer calls completion(nil)<br>                return<br>            }<br>            guard let data = data else {<br>                // still nil, defer calls completion(nil)<br>                return<br>            }<br>            result = data<br>            // defer calls completion(data)<br>        }<br>        task.resume()<br>    }<br>}</pre><p>This ensures the completion closure is written only once in the code. Every return path executes the defer, guaranteeing one call to completion per task closure.</p><p>If you want to be extra safe (for example, in rare cases where completion handlers could trigger multiple times), you can use a lock and flag around the completion(result) inside the defer, but the general pattern above is correct for typical URLSession use.</p><h3>8. Can We Remove DispatchQueue.main.async while updating the UI?</h3><p>If you’re calling loadData from a UIViewController and updating UI afterward:</p><pre>DispatchQueue.main.async {<br>    self.tableView.reloadData()<br>}</pre><p>You can often remove it if your function or method is already @MainActor isolated:</p><pre>@MainActor<br>func updateUI() {<br>    tableView.reloadData()<br>}</pre><p>Because UIViewController and most UIKit classes are implicitly @MainActor, code inside their methods already runs on the main thread.</p><p>Hope this article made your Swift journey &amp; interview preparation a bit smoother. Until next time — happy Swifting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76fbefd6e428" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom NotificationCenter in swift]]></title>
            <link>https://medium.com/@aayushi9555/custom-notificationcenter-in-swift-1d0651218d80?source=rss-2736a3f91944------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d0651218d80</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[notifications]]></category>
            <dc:creator><![CDATA[Aayushi: iOS Developer]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 17:23:13 GMT</pubDate>
            <atom:updated>2025-09-19T03:48:17.615Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever prepared for senior iOS interviews, you’ve likely come across this classic question:</p><blockquote><em>“Can you implement a custom NotificationCenter in Swift?”</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d-S9vqevFDKBgxMv" /></figure><p>At first glance, it sounds straightforward — after all, Apple already gives us NotificationCenter. But once you start building it from scratch, the complexity shows up quickly:</p><ul><li>How do you handle observers without leaking memory?</li><li>How do you keep it thread-safe?</li><li>How do you simulate the familiar API with addObserver, removeObserver, and post?</li><li>And of course, how do you avoid crashes while calling selectors dynamically?</li></ul><p>In this article, I’ll walk you through a <strong>lightweight, custom NotificationCenter in Swift</strong>, breaking it down into small, easy-to-understand parts. By the end, you’ll not only have a working implementation but also a strong interview story to tell.</p><h3>The Setup: Broadcaster and Observers</h3><p>Let’s start with two simple observer classes and a broadcaster that triggers the event.</p><pre>class BroadCaster {<br>    func notify() {<br>        CustomNotificationCenter.shared.post(Notification.Name(&quot;customEvent&quot;))<br>    }<br>}<br><br>class Observer1 {<br>    init() {<br>        CustomNotificationCenter.shared.addObserver(self, selector: #selector(notificationReceived), name: Notification.Name(&quot;customEvent&quot;))<br>    }<br>    <br>    @objc func notificationReceived() {<br>        print(&quot;Notification received by Observer1&quot;)<br>    }<br>    <br>    deinit {<br>        print(&quot;Observer1 deinit&quot;)<br>        CustomNotificationCenter.shared.removeObserver(self)<br>    }<br>}<br>class Observer2 {<br>    init() {<br>        CustomNotificationCenter.shared.addObserver(self, selector: #selector(notificationReceived), name: Notification.Name(&quot;customEvent&quot;))<br>    }<br>    <br>    @objc func notificationReceived() {<br>        print(&quot;Notification received by Observer2&quot;)<br>    }<br>    <br>    deinit {<br>        print(&quot;Observer2 deinit&quot;)<br>        CustomNotificationCenter.shared.removeObserver(self)<br>    }<br>}</pre><p>Nothing fancy here. Both observers listen for the same customEvent. The broadcaster posts the event.</p><h3>Storing Observers Safely</h3><p>The first challenge is <strong>holding onto observers without creating retain cycles</strong>. If we store observers strongly, they’ll never deallocate. So instead, we create a lightweight wrapper with a weak reference:</p><pre>private class Observer {<br>    weak var observer: AnyObject?<br>    let selector: Selector<br><br>    init(observer: AnyObject, selector: Selector) {<br>        self.observer = observer<br>        self.selector = selector<br>    }<br>}</pre><p>This ensures that once an observer is deallocated, it naturally falls off without us holding it hostage.</p><h3>The Custom Notification Center</h3><p>Here’s the full implementation:</p><pre>class CustomNotificationCenter {<br>    <br>    nonisolated(unsafe) static let shared = CustomNotificationCenter()<br>    <br>    // Protect observers dictionary with a serial queue for thread safety<br>    private let queue = DispatchQueue(label: &quot;com.customnotificationcenter.queue&quot;)<br>    private var observers: [Notification.Name: [Observer]] = [:]<br>    <br>    private init() {}<br>    <br>    func addObserver(_ observer: AnyObject, selector: Selector, name: Notification.Name) {<br>        queue.sync {<br>            let newObserver = Observer(observer: observer, selector: selector)<br>            observers[name, default: []].append(newObserver)<br>        }<br>    }<br>    <br>    func post(_ name: Notification.Name) {<br>        var observersList: [Observer] = []<br>        <br>        queue.sync {<br>            // Clean up nil observers before posting<br>            observers[name] = observers[name]?.filter { $0.observer != nil }<br>            observersList = observers[name] ?? []<br>        }<br>        <br>        // Notify outside the lock to prevent deadlocks<br>        for entry in observersList {<br>            entry.observer?.perform(entry.selector)<br>        }<br>    }<br>    <br>    func removeObserver(_ observer: AnyObject) {<br>        queue.sync {<br>            for name in observers.keys {<br>                observers[name]?.removeAll { $0.observer === observer || $0.observer == nil }<br>            }<br>        }<br>    }<br>}</pre><p>Let’s break down the interesting parts:</p><ol><li><strong>Thread Safety</strong>: All mutations to the observers dictionary happen inside a private serial queue. This prevents race conditions if multiple observers are added/removed simultaneously.</li><li><strong>Weak Storage</strong>: Observers are weakly held, so deinit works naturally. No retain cycles, no memory leaks.</li><li><strong>Post Outside Lock</strong>: The actual selector call happens outside queue.sync. This avoids deadlocks if a selector internally tries to post another notification.</li></ol><h3>Handling the Delay</h3><p>In my testing, I noticed that if I immediately posted after setting an observer to nil, the deinit wasn’t fully registered yet. So I added a tiny delay:</p><pre>observer1 = nil<br>DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {<br>    broadcaster.notify()<br>}</pre><p>This gives the runtime enough time to clean up the weak reference before the next event. Without this, you may sometimes see ghost notifications.</p><p>This is a subtle but important reminder that <strong>object deallocation isn’t always instantaneous in practice</strong> — especially when async queues are involved.</p><h3>Putting It All Together</h3><p>Finally, here’s how everything plays out:</p><pre>let broadcaster = BroadCaster()<br><br>var observer1: Observer1? = Observer1()<br>let observer2: Observer2? = Observer2()<br>broadcaster.notify() // Both Observer1 and Observer2 get the event<br>observer1 = nil<br>DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {<br>    broadcaster.notify() // Only Observer2 receives the event<br>}</pre><p>Output:</p><pre>Notification received by Observer1<br>Notification received by Observer2<br>Observer1 deinit<br>Notification received by Observer2</pre><h3>Why This Matters</h3><p>Rebuilding NotificationCenter from scratch is not about replacing Apple’s implementation—it’s about <strong>deepening your understanding of iOS internals</strong>.</p><p>This exercise touches on critical engineering concepts that senior developers are expected to master:</p><ul><li>Memory management with weak references</li><li>Thread safety and synchronization</li><li>Avoiding deadlocks in async code</li></ul><p>So, if this comes up in your next interview, you’ll not only show that you can code it — but also that you truly understand <em>why</em> each part exists.</p><p>Hope this article made your Swift journey &amp; interview preparation a bit smoother. Until next time — happy Swifting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d0651218d80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom High Order Filter Function in Swift]]></title>
            <link>https://medium.com/@aayushi9555/custom-high-order-filter-function-in-swift-b0129e891562?source=rss-2736a3f91944------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0129e891562</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Aayushi: iOS Developer]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 17:51:13 GMT</pubDate>
            <atom:updated>2025-09-17T17:51:13.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rA8d2l4EcrKe3JyF" /></figure><blockquote>A yet common interview question. Since you have decided to read this article, I’m sure you know about the filter function provided by Swift. If not, here’s a quick recap:</blockquote><p>The filter function returns an array containing only the elements that satisfy a given condition. It’s commonly used to extract specific values from a collection based on a rule or predicate.</p><p>Now let’s get started with the code.</p><h3>🛠️ Creating Custom Filter Function</h3><p>Here’s a simple custom version of filter as a standalone function:</p><pre>func customFilter&lt;T&gt;(_ elements: [T], _ isIncluded: (T) -&gt; Bool) -&gt; [T] {<br>    var result: [T] = []<br>    for element in elements {<br>        if isIncluded(element) {<br>            result.append(element)<br>        }<br>    }<br>    return result<br>}</pre><h3>✅ Usage Examples</h3><pre>// Example 1: Filtering even numbers<br>let numbers = [1, 2, 3, 4, 5]<br>let evens = customFilter(numbers) { $0 % 2 == 0 }<br>print(&quot;Evens: \(evens)&quot;)<br>// Example 2: Strings longer than 5 characters<br>let fruits = [&quot;apple&quot;, &quot;banana&quot;, &quot;kiwi&quot;]<br>let longFruits = customFilter(fruits) { $0.count &gt; 5 }<br>print(&quot;Long Fruits: \(longFruits)&quot;)</pre><h3>🔄 Bonus: Using Extension for Cleaner Syntax</h3><p>We can enhance this by attaching the filter behavior directly to arrays:</p><pre>extension Array {<br>    func myFilter&lt;T&gt;(_ isIncluded: (T) -&gt; Bool) -&gt; [T] {<br>        var result: [T] = []<br>        for element in self {<br>            if isIncluded(element as! T) {<br>                result.append(element as! T)<br>            }<br>        }<br>        return result<br>    }<br>}</pre><h3>Usage:</h3><pre>let nums = [10, 15, 20]<br>let filtered = nums.myFilter { (num: Int) in num &gt; 10 }<br>print(&quot;Filtered: \(filtered)&quot;)</pre><h3>🧩 Key Difference</h3><p>Instead of passing the array as a parameter, extending Array makes the usage more <strong>Swifty </strong>and often comes as a followup question by the interviewer:</p><ul><li>✅ customFilter(arr) { ... } → <strong>Function</strong></li><li>✅ arr.myFilter { ... } → <strong>Extension Method</strong></li></ul><p>Next: <a href="https://medium.com/@aayushi9555/custom-high-order-map-function-in-swift-63fb59a6284b">Custom Map Function</a></p><p>Hope this article made your Swift journey &amp; interview preparation a bit smoother. Until next time — happy Swifting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0129e891562" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Chess Game in iOS Swift — A Low Level System Design Interview Problem]]></title>
            <link>https://medium.com/@aayushi9555/designing-a-chess-game-in-ios-swift-a-low-level-system-design-interview-problem-f1632e51ee30?source=rss-2736a3f91944------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1632e51ee30</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[iasinterview]]></category>
            <category><![CDATA[low-level-design]]></category>
            <dc:creator><![CDATA[Aayushi: iOS Developer]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 16:18:02 GMT</pubDate>
            <atom:updated>2025-09-19T04:13:39.262Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing a Chess Game in iOS Swift — A Low Level System Design Interview Problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jjbjo6R_LClHIu1R" /></figure><p><strong>Low-level system design</strong> is a standard interview round at companies like <strong>Microsoft, Google, Walmart, and Amazon</strong> — even for mobile developers. The challenge for iOS engineers is that there aren’t many resources tailored to this area. One popular exercise interviewers often use is designing a <strong>chess game</strong>, since it really brings out how well you can model objects, split up responsibilities, and think ahead about extensibility.</p><p>In this article, we’ll walk through the problem step by step, starting with requirements, then exploring architecture and finally implementing it in Swift.</p><h3>1. Requirements and Use Cases</h3><h3>Functional Requirements</h3><ul><li>An <strong>8x8 chessboard</strong>.</li><li><strong>Two players</strong>, each controlling a set of standard chess pieces.</li><li>Pieces must move according to their specific rules (Pawn, Rook, Knight, Bishop, Queen, King).</li><li>The game must <strong>track player turns</strong>.</li><li>The system should detect <strong>game-ending conditions</strong>:</li><li>Check</li><li>Checkmate</li><li>Stalemate</li></ul><h3>Non-Functional Requirements</h3><ul><li><strong>Extensibility</strong>: Should allow new features like an AI opponent or different time-based modes.</li><li><strong>Separation of Concerns</strong>: Game logic (Model) should be independent of UI (View/Controller). This is critical in <strong>iOS development (MVC or MVVM)</strong>.</li><li><strong>Reusability</strong>: Core chess logic should be testable without a UI layer.</li></ul><h3>2. Core Components and Architecture</h3><p>In Swift, we’ll combine <strong>classes (reference types)</strong> and <strong>structs (value types)</strong> for clarity and safety.</p><ul><li><strong>Game (class)</strong><br> The main engine managing state, flow, and turns.</li><li><strong>Board (class)</strong><br> Represents the 8x8 grid, holding pieces and handling piece placement.</li><li><strong>Square (struct)</strong><br> Immutable coordinate on the board (row, col).</li><li><strong>Piece (protocol + class hierarchy)</strong><br> Protocol defines required behavior (canMove). Specific pieces (King, Queen, Rook, etc.) subclass a base Piece class.</li><li><strong>Player (struct)</strong><br> Represents each player (white or black).</li><li><strong>Move (struct)</strong><br> Represents movement from one square to another.</li></ul><h3>3. Class Diagram</h3><p>Below is a conceptual class diagram showing relationships:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*fgJ6xtPxllPD59Dk9DpJpA.png" /></figure><h3>4. Swift Implementation</h3><p>Here’s a <strong>Swift skeleton implementation</strong>:</p><pre>import Foundation<br>// MARK: - Supporting Types<br>enum Color {<br>    case white, black<br>}<br>enum PieceType {<br>    case king, queen, rook, bishop, knight, pawn<br>}<br>struct Square {<br>    let row: Int<br>    let col: Int<br>}<br>struct Move {<br>    let start: Square<br>    let end: Square<br>}<br>struct Player {<br>    let color: Color<br>}<br>// MARK: - Piece Protocol and Base Class<br>protocol Piece {<br>    var color: Color { get }<br>    var type: PieceType { get }<br>    func canMove(from: Square, to: Square, on board: Board) -&gt; Bool<br>}<br>class BasePiece: Piece {<br>    let color: Color<br>    let type: PieceType<br>    <br>    init(color: Color, type: PieceType) {<br>        self.color = color<br>        self.type = type<br>    }<br>    <br>    func canMove(from: Square, to: Square, on board: Board) -&gt; Bool {<br>        // Default implementation, overridden by subclasses<br>        return false<br>    }<br>}<br>// Example: Rook<br>class Rook: BasePiece {<br>    override func canMove(from: Square, to: Square, on board: Board) -&gt; Bool {<br>        return from.row == to.row || from.col == to.col<br>    }<br>}<br>// MARK: - Board<br>class Board {<br>    private var grid: [[Piece?]] = Array(<br>        repeating: Array(repeating: nil, count: 8),<br>        count: 8<br>    )<br>    <br>    func getPiece(at square: Square) -&gt; Piece? {<br>        return grid[square.row][square.col]<br>    }<br>    <br>    func setPiece(_ piece: Piece?, at square: Square) {<br>        grid[square.row][square.col] = piece<br>    }<br>}<br>// MARK: - Game<br>enum GameStatus {<br>    case active, checkmate, stalemate<br>}<br>class Game {<br>    private var board = Board()<br>    private var currentPlayer: Player<br>    private(set) var status: GameStatus = .active<br>    <br>    init(firstPlayer: Player) {<br>        self.currentPlayer = firstPlayer<br>    }<br>    <br>    func makeMove(_ move: Move) {<br>        guard let piece = board.getPiece(at: move.start) else { return }<br>        <br>        if piece.canMove(from: move.start, to: move.end, on: board) {<br>            board.setPiece(nil, at: move.start)<br>            board.setPiece(piece, at: move.end)<br>            switchPlayer()<br>        }<br>    }<br>    <br>    private func switchPlayer() {<br>        currentPlayer = (currentPlayer.color == .white)<br>            ? Player(color: .black)<br>            : Player(color: .white)<br>    }<br>}</pre><h3>5. Key Takeaways for Interviews</h3><ul><li><strong>Clarify requirements first</strong> (don’t over-engineer).</li><li><strong>Separate model from UI</strong> (vital in mvvm).</li><li><strong>Use protocols and inheritance wisely</strong>: protocols for flexibility, base classes for shared code.</li><li><strong>Think about extensibility</strong>: AI opponent, move history, PGN export, etc. <strong><em>PGN (Portable Game Notation)</em></strong><em> is a plain-text format used to record and share chess games. It includes both metadata (like player names, date, and result) and the full sequence of moves in standard chess notation. PGN makes games portable — any chess software can read it, allowing players to review, analyze, or share their matches easily.</em></li></ul><p>✅ With this design, you have a clear, extensible architecture for a chess game in Swift — ready for <strong>system design interviews</strong> at top tech companies.</p><p>Hope this article made your Swift journey &amp; interview preparation a bit smoother. Until next time — happy Swifting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1632e51ee30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The iOS Architecture That Gets You Hired (MVVM-C + A)]]></title>
            <link>https://medium.com/@aayushi9555/the-ios-architecture-that-gets-you-hired-mvvm-c-a-323dfa09eff8?source=rss-2736a3f91944------2</link>
            <guid isPermaLink="false">https://medium.com/p/323dfa09eff8</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[iasinterview]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Aayushi: iOS Developer]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 15:42:05 GMT</pubDate>
            <atom:updated>2025-09-17T04:07:32.586Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSLrXLWYxY7KXtWVSYPzMA.png" /></figure><p>If you want a clean, testable iOS architecture to discuss in interviews — and actually use in production — <strong>MVVM with a Coordinator and an Assembly/Factory layer</strong> is the gold standard.</p><p>It separates responsibilities, makes testing a breeze, and scales beautifully. It’s no wonder teams at major tech companies favour modular, dependency-injected designs for long-term maintainability. Understanding <em>why</em> these pieces exist and <em>how</em> they fit together will make a powerful impression.</p><p>Below I walk through the Payment example step-by-step, explain dependency injection (DI) clearly and give small code snippets for each component. The Core Components</p><ul><li><strong>Model:</strong> Simple data structures.</li><li><strong>View:</strong> The UI (UIViewController), delegates user actions.</li><li><strong>ViewModel:</strong> UI logic, state management. No UIKit.</li><li><strong>Service:</strong> Business logic, networking, database.</li><li><strong>Coordinator:</strong> Navigation logic.</li><li><strong>Assembly/Factory:</strong> Creates and connects objects (DI).</li></ul><h4>Component diagram (high level)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*mhdCJKzJW8i7ZMgdRDprog.png" /></figure><h3>Step 1: The Foundation (Model &amp; Service Protocol)</h3><p>First, define the data structures and the contract for our business logic.</p><pre>// Model<br>struct User {<br>    let id: Int<br>    let name: String<br>    var balance: Double<br>}<br><br>// Error<br>enum PaymentError: Error {<br>    case userNotFound<br>    case invalidAmount<br>    case insufficientBalance<br>}<br><br>// Service Contract<br>protocol PaymentServiceProtocol {<br>    func makePayment(fromId: Int, toId: Int, amount: Double) throws<br>    func getTransactions() -&gt; [String]<br>}</pre><h3>Step 2: The Logic (Service &amp; ViewModel)</h3><p>The PaymentService implements the business rules. The PaymentViewModel prepares data for the UI and depends only on the protocol, not the concrete service.</p><pre>// Concrete Service<br>final class PaymentService: PaymentServiceProtocol {<br>    private var users: [User] = [<br>        User(id: 1, name: &quot;Alice&quot;, balance: 500),<br>        User(id: 2, name: &quot;Bob&quot;, balance: 200)<br>    ]<br>    <br>    private var transactions: [String] = []<br>    <br>    func makePayment(fromId: Int, toId: Int, amount: Double) throws {<br>        guard amount &gt; 0 else { throw PaymentError.invalidAmount }<br>        guard var fromUser = users.first(where: { $0.id == fromId }) else { throw PaymentError.userNotFound }<br>        guard fromUser.balance &gt;= amount else { throw PaymentError.insufficientBalance }<br>        // ... implementation to transfer funds<br>        transactions.append(&quot;Payment: \(amount) from \(fromId) to \(toId)&quot;)<br>    }<br>    func getTransactions() -&gt; [String] {<br>        return transactions<br>    }<br>}<br><br>// ViewModel<br>final class PaymentViewModel {<br>    private let service: PaymentServiceProtocol<br>    var onPaymentResult: ((Result&lt;String, PaymentError&gt;) -&gt; Void)?<br>    var onTransactionsUpdated: (([String]) -&gt; Void)?<br>    init(service: PaymentServiceProtocol) {<br>        self.service = service<br>    }<br>    func makePayment(from fromId: Int, to toId: Int, amount: Double) {<br>        DispatchQueue.global().async { [weak self] in<br>            do {<br>                try self?.service.makePayment(fromId: fromId, toId: toId, amount: amount)<br>                let message = &quot;Payment successful.&quot;<br>                DispatchQueue.main.async {<br>                    self?.onPaymentResult?(.success(message))<br>                    self?.onTransactionsUpdated?(self?.service.getTransactions() ?? [])<br>                }<br>            } catch let error as PaymentError {<br>                DispatchQueue.main.async {<br>                    self?.onPaymentResult?(.failure(error))<br>                }<br>            } catch {}<br>        }<br>    }<br>}</pre><h3>Step 3: The UI (View)</h3><p>The PaymentViewController is responsible only for displaying UI and forwarding user events to the ViewModel. It receives the ViewModel through its initializer.</p><pre>final class PaymentViewController: UIViewController {<br>    private let viewModel: PaymentViewModel<br>    private let statusLabel = UILabel()<br>    private let payButton = UIButton(type: .system)<br>    init(viewModel: PaymentViewModel) {<br>        self.viewModel = viewModel<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>    <br>    required init?(coder: NSCoder) { fatalError(&quot;init(coder:) has not been implemented&quot;) }<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        bindViewModel()<br>        // ... UI setup for button target etc.<br>    }<br>    private func bindViewModel() {<br>        viewModel.onPaymentResult = { [weak self] result in<br>            switch result {<br>            case .success(let message):<br>                self?.statusLabel.text = message<br>            case .failure(let error):<br>                self?.statusLabel.text = &quot;Error: \(error)&quot;<br>            }<br>        }<br>    }<br>    @objc private func payButtonTapped() {<br>        viewModel.makePayment(from: 1, to: 2, amount: 150)<br>    }<br>}</pre><h3>Step 4: The Wiring (Assembly &amp; Coordinator)</h3><p>The Assembly builds the feature module. The Coordinator directs navigation.</p><pre>// Assembly<br>protocol AssemblyProtocol {<br>    func buildPaymentModule() -&gt; UIViewController<br>}<br><br>final class Assembly: AssemblyProtocol {<br>    private let paymentService: PaymentServiceProtocol = PaymentService()<br>    func buildPaymentModule() -&gt; UIViewController {<br>        let viewModel = PaymentViewModel(service: paymentService)<br>        let viewController = PaymentViewController(viewModel: viewModel)<br>        return viewController<br>    }<br>}<br><br>// Coordinator<br>final class AppCoordinator {<br>    private let window: UIWindow<br>    private let assembly: AssemblyProtocol<br>    init(window: UIWindow, assembly: AssemblyProtocol) {<br>        self.window = window<br>        self.assembly = assembly<br>    }<br>    func start() {<br>        let paymentVC = assembly.buildPaymentModule()<br>        window.rootViewController = UINavigationController(rootViewController: paymentVC)<br>        window.makeKeyAndVisible()<br>    }<br>}</pre><h3>Step 5: Proving It Works (Unit Testing)</h3><p>Because we used DI, we can swap the real service for a mock to test our ViewModel’s logic in isolation.</p><p>Swift</p><pre>// Mock Service (in Test Target)<br>class MockPaymentService: PaymentServiceProtocol {<br>    var makePaymentShouldSucceed = true<br>    var makePaymentCallCount = 0<br>    func makePayment(fromId: Int, toId: Int, amount: Double) throws {<br>        makePaymentCallCount += 1<br>        if !makePaymentShouldSucceed {<br>            throw PaymentError.insufficientBalance<br>        }<br>    }<br>    func getTransactions() -&gt; [String] { return [] }<br>}<br><br>// ViewModel Test (in Test Target)<br>class PaymentViewModelTests: XCTestCase {<br>    var viewModel: PaymentViewModel!<br>    var mockService: MockPaymentService!<br>    override func setUp() {<br>        super.setUp()<br>        mockService = MockPaymentService()<br>        viewModel = PaymentViewModel(service: mockService)<br>    }<br>    <br>    func testMakePayment_Success() {<br>        mockService.makePaymentShouldSucceed = true<br>        var result: Result&lt;String, PaymentError&gt;?<br>        let expectation = self.expectation(description: &quot;Success callback&quot;)<br>        <br>        viewModel.onPaymentResult = { res in<br>            result = res<br>            expectation.fulfill()<br>        }<br>        viewModel.makePayment(from: 1, to: 2, amount: 100)<br>        <br>        waitForExpectations(timeout: 1.0)<br>        <br>        XCTAssertEqual(mockService.makePaymentCallCount, 1)<br>        guard case .success = result else { return XCTFail() }<br>    }<br><br>    func testMakePayment_Failure() {<br>        mockService.makePaymentShouldSucceed = false<br>        var result: Result&lt;String, PaymentError&gt;?<br>        let expectation = self.expectation(description: &quot;Failure callback&quot;)<br>        viewModel.onPaymentResult = { res in<br>            result = res<br>            expectation.fulfill()<br>        }<br>        viewModel.makePayment(from: 1, to: 2, amount: 100)<br>        waitForExpectations(timeout: 1.0)<br>        XCTAssertEqual(mockService.makePaymentCallCount, 1)<br>        guard case .failure(let error) = result else { return XCTFail() }<br>        XCTAssertEqual(error, .insufficientBalance)<br>    }<br>}</pre><h3>Wrapping It All Up</h3><p>By combining <strong>MVVM + Coordinator + Assembly (Factory with DI)</strong>, you achieve:</p><ul><li>A <strong>clear separation of concerns</strong> — View just displays, ViewModel just handles state, Service just does business logic.</li><li><strong>Dependency Injection</strong> — making everything testable with mocks, no hidden dependencies.</li><li><strong>Scalable navigation</strong> — the Coordinator owns the flow instead of bloated ViewControllers.</li><li><strong>Consistent module creation</strong> — Assembly ensures every module is built in the same way.</li></ul><p>This is why companies like <strong>Microsoft, Walmart, and other large-scale engineering orgs</strong> adopt these patterns. In interviews, showing that you understand <em>not just MVVM, but MVVM-C+A with DI</em> immediately sets you apart — it signals that you think about long-term maintainability, testability, and scalability.</p><p>So, next time an interviewer asks about architecture, don’t just say <em>“I use MVVM”</em>. Walk them through how <strong>Coordinators handle navigation, Assemblies inject dependencies, and ViewModels stay testable</strong>.</p><p>Hope this article made your Swift journey a bit smoother. Until next time — happy Swifting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=323dfa09eff8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Concurrency Interview Cheatsheet]]></title>
            <link>https://medium.com/@aayushi9555/swift-concurrency-interview-cheatsheet-16d30e258988?source=rss-2736a3f91944------2</link>
            <guid isPermaLink="false">https://medium.com/p/16d30e258988</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-interview]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-interview-question]]></category>
            <category><![CDATA[asyncawait]]></category>
            <dc:creator><![CDATA[Aayushi: iOS Developer]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 09:10:17 GMT</pubDate>
            <atom:updated>2025-09-14T15:46:37.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TAsZRkaeLUy9e9zX" /></figure><blockquote>E<em>very iOS developer has faced this: “You have three APIs — call them one after the other, but API 1 and API 2 can run in parallel, and API 3 must wait for both to finish. How will you do it in Swift?”</em></blockquote><p>This classic interview question tests your understanding of <strong>concurrency</strong>, <strong>synchronization</strong>, and <strong>modern Swift patterns</strong>. In this post , I’ll break down <strong>multiple approaches </strong>for similar interview questions, from old-school GCD to modern async/await, with examples.</p><h3>Q1. Call API 1 → 2 → 3 sequentially</h3><h4>1. Nested Closures</h4><pre>api1 { res1 in<br>    api2 { res2 in<br>        api3 { res3 in<br>            print(&quot;All done&quot;)<br>        }<br>    }<br>}</pre><p><strong>✅ Pros:</strong> Simple, easy to read for 2–3 calls.<br> <strong>❌ Cons:</strong> Callback hell, poor maintainability.</p><h4>2. DispatchQueue + Completion</h4><pre>func callSequential() {<br>    DispatchQueue.global().async {<br>        api1 { result1 in<br>            api2 { result2 in<br>                api3 { result3 in<br>                    print(&quot;All done&quot;)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>✅ Pros:</strong> Works with GCD, no 3rd party needed. It’s only pro above nested closure it that it will not block the UI.<br> <strong>❌ Cons:</strong> Still nesting, weak error handling.</p><h4>3. OperationQueue (dependencies)</h4><pre>let op1 = BlockOperation { api1 { _ in } }<br>let op2 = BlockOperation { api2 { _ in } }<br>let op3 = BlockOperation { api3 { _ in } }<br>op2.addDependency(op1)<br>op3.addDependency(op2)<br>queue.addOperations([op1, op2, op3], waitUntilFinished: false)</pre><p><strong>✅ Pros:</strong> Clear dependencies, scalable.<br> <strong>❌ Cons:</strong> More boilerplate, heavy for small tasks.</p><h4>4. Async/Await</h4><pre>func fetchAll() async {<br>    let r1 = await api1()<br>    let r2 = await api2()<br>    let r3 = await api3()<br>}</pre><p><strong>✅ Pros:</strong> Clean, linear, easy debugging.<br> <strong>❌ Cons:</strong> iOS 15+, need structured concurrency.</p><h3>Q2. Call API 1 &amp; 2 in parallel → then call 3</h3><h4>1. DispatchGroup</h4><pre>let group = DispatchGroup()<br>group.enter(); api1 { _ in group.leave() }<br>group.enter(); api2 { _ in group.leave() }<br>group.notify(queue: .main) {<br>    api3 { _ in }<br></pre><p><strong>✅ Pros:</strong> Classic, widely known.<br> <strong>❌ Cons:</strong> Boilerplate, must balance enter/leave.</p><h4>2. Async/Await (parallel)</h4><pre>async {<br>    async let r1 = api1()<br>    async let r2 = api2()<br>    let _ = await (r1, r2)<br>    await api3()<br>}</pre><p><strong>✅ Pros:</strong> Minimal, safe, modern.<br> <strong>❌ Cons:</strong> iOS 15+, async APIs required.</p><h4>3. OperationQueue</h4><pre>let op1 = BlockOperation { api1 { _ in } }<br>let op2 = BlockOperation { api2 { _ in } }<br>let op3 = BlockOperation { api3 { _ in } }<br>op3.addDependency(op1)<br>op3.addDependency(op2)<br>queue.addOperations([op1, op2, op3], waitUntilFinished: false)</pre><p><strong>✅ Pros:</strong> Explicit dependency mgmt.<br> <strong>❌ Cons:</strong> Heavyweight, verbose.</p><h3>Q3. Call API 1 &amp; 2 in parallel → Call 3 after both complete (even if one fails)</h3><h4>1. DispatchGroup with error handling inside</h4><pre>let group = DispatchGroup()<br>var res1: Result&lt;Data, Error&gt;?<br>var res2: Result&lt;Data, Error&gt;?<br>group.enter(); api1 { r in res1 = r; group.leave() }<br>group.enter(); api2 { r in res2 = r; group.leave() }<br>group.notify(queue: .main) {<br>    api3 { _ in }<br>}</pre><p><strong>✅ Pros:</strong> Control both success/failure.<br> <strong>❌ Cons:</strong> Manual error tracking.</p><h4>2. Async/Await with try?</h4><pre>async {<br>    async let r1 = try? api1()<br>    async let r2 = try? api2()<br>    let _ = await (r1, r2)<br>    await api3()<br>}</pre><p><strong>✅ Pros:</strong> Super clean, ignores failures gracefully.<br> <strong>❌ Cons:</strong> Risk of silently swallowing errors.</p><h4>3. Combine (Zip)</h4><pre>Publishers.Zip(api1Publisher, api2Publisher)<br>    .replaceError(with: (&quot;fallback1&quot;, &quot;fallback2&quot;))<br>    .sink { _ in api3 { _ in } }</pre><p><strong>✅ Pros:</strong> Reactive, failure-handling via replaceError.<br> <strong>❌ Cons:</strong> Overkill if not already using Combine.</p><p>👉 This way you have <strong>multiple approaches per scenario</strong>, with pros/cons to pick the best depending on the interview context.</p><p>Hope this article made your Swift journey a bit smoother. Until next time — happy Swifting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16d30e258988" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Download Manager in iOS with Swift — Mobile System Design]]></title>
            <link>https://medium.com/@aayushi9555/building-a-download-manager-in-ios-with-swift-mobile-system-design-36f4e1a5a59c?source=rss-2736a3f91944------2</link>
            <guid isPermaLink="false">https://medium.com/p/36f4e1a5a59c</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-system-design]]></category>
            <dc:creator><![CDATA[Aayushi: iOS Developer]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 08:20:46 GMT</pubDate>
            <atom:updated>2025-09-14T15:49:38.321Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Download Manager in iOS with Swift — Mobile System Design</h3><blockquote>⚠️ Disclaimer: This post is for <strong>my own learning and revision</strong>. It is based on the excellent explanation in <a href="https://youtu.be/hESp_R8CMm0?si=cqjTc3udPj8P7u6M">this YouTube video</a>. All credit goes to the creator of the video. I am simply documenting the system design process for future reference.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PSfwjxA2L1dwRpZg" /></figure><h3>📌 Requirement Gathering</h3><p><strong>Content type</strong>: Only books (text files, not media).<br><strong>File size</strong>: 20 KB — 200 MB.<br><strong>Threshold</strong>: Take input from user.<br><strong>Simultaneous downloads</strong>: ❌ Not supported.<br><strong>Background downloads</strong>: ✅ Supported.<br><strong>Features</strong>: Pause / Resume / Delete.<br><strong>Resume after app kill</strong>: ✅ Supported.<br><strong>Users</strong>: SDK should be reusable and independent.<br><strong>Metadata</strong>: Shown from API (not frequently updated → can use SQL DB).<br><strong>Encryption</strong>: Files are non-encrypted.</p><h3>📌 Scope</h3><ul><li>Build a <strong>framework (SDK)</strong> to handle downloads.</li><li>Only <strong>text files</strong> (not photos/videos/media).</li><li><strong>Serial downloads</strong> (one at a time).</li><li>Must support <strong>pause, resume, delete</strong>.</li></ul><h3>📌 Technical Requirements</h3><ul><li>Networking → URLSessionDownloadTask.</li><li>Queueing → Serial DispatchQueue.</li><li>Database → <strong>SQLite</strong> to store download info (content ID, URL, progress, local path).</li><li>Resume downloads → Store state in DB.</li><li>Offline support → Download continues in background when network is restored.</li><li>Disk operations → FileManager.</li></ul><h3>📌 High-Level Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qvi671hRp4EEk9Zt" /></figure><h3>Components</h3><p><strong>DownloadManager (Singleton)</strong></p><ul><li>Exposes public APIs → start, pause, resume, cancel.</li><li>Registers listeners for UI updates.</li><li>Delegates work to DownloadService.</li></ul><p><strong>DownloadService</strong></p><ul><li>Handles URLSessionDownloadTask.</li><li>Communicates progress back to manager.</li><li>Manages background downloads.</li><li>Handles listeners (weak references to prevent memory leaks).</li></ul><p><strong>StorageService</strong></p><ul><li>Handles <strong>CRUD</strong> operations for DB.</li><li>Manages disk storage (delete, check free space, fetch directory path).</li><li>⚠️ Note: This violates <strong>Single Responsibility Principle (SRP)</strong> since it handles both DB &amp; Disk.</li></ul><p><strong>Database Helper</strong></p><ul><li>Wrapper around SQLite.</li><li>Stores metadata: id, url, progress, filePath.</li></ul><h3>📌 Example Low-Level Design: StorageService</h3><pre>import Foundation<br>import SQLite3<br><br>class StorageService {<br>    static let shared = StorageService()<br>    // MARK: - Database Operations<br>    func saveDownload(id: String, url: String, progress: Double, path: String) {<br>        // Insert or update DB record<br>    }<br>    func fetchDownload(id: String) -&gt; DownloadModel? {<br>        // Query SQLite<br>        return nil<br>    }<br>    func deleteDownload(id: String) {<br>        // Delete from DB &amp; disk<br>    }<br>    // MARK: - Disk Operations<br>    func deleteFromDisk(path: String) {<br>        try? FileManager.default.removeItem(atPath: path)<br>    }<br>    func availableDiskSpace() -&gt; Int64 {<br>        if let attrs = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()),<br>           let freeSize = attrs[.systemFreeSize] as? Int64 {<br>            return freeSize<br>        }<br>        return 0<br>    }<br>    func getDirectoryPath() -&gt; String {<br>        return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? &quot;&quot;<br>    }<br>}</pre><h3>📌 Open Questions</h3><ul><li><strong>Listeners</strong>: When VC changes, how does a new VC listen? → Register multiple weak listeners.</li><li><strong>SRP Violation</strong>: Should disk operations move to another service?</li><li><strong>Scalability</strong>: How to extend for parallel downloads in future?→Use a <strong>dictionary keyed by </strong><strong>contentId mapping to </strong><strong>DownloadTask objects</strong>, enabling O(1) lookup and management of multiple parallel downloads simultaneously.</li></ul><h3>✅ Key Takeaways</h3><ul><li>Keep <strong>DownloadManager</strong> as entry point.</li><li><strong>DownloadService</strong> does networking.</li><li><strong>StorageService</strong> persists data &amp; manages disk.</li><li>SQLite ensures resume support.</li><li>Weak listeners prevent retain cycles.</li></ul><p>📺 Reference Video: <a href="https://youtu.be/hESp_R8CMm0?si=cqjTc3udPj8P7u6M">System Design for iOS Download Manager</a></p><p>Hope this article made your Swift journey a bit smoother. Until next time — happy Swifting! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36f4e1a5a59c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>