<?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 Sejal Khanna on Medium]]></title>
        <description><![CDATA[Stories by Sejal Khanna on Medium]]></description>
        <link>https://medium.com/@sejallkhanna?source=rss-f9615d0bfa9e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*f-ViByYcNqOZjoekOjOg5Q.png</url>
            <title>Stories by Sejal Khanna on Medium</title>
            <link>https://medium.com/@sejallkhanna?source=rss-f9615d0bfa9e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:31:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sejallkhanna/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 Internals & State Management: Why Your Views “Randomly” Recreate]]></title>
            <link>https://sejallkhanna.medium.com/swiftui-internals-state-management-why-your-views-randomly-recreate-71630303b04c?source=rss-f9615d0bfa9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/71630303b04c</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sejal Khanna]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 05:42:05 GMT</pubDate>
            <atom:updated>2026-03-28T05:42:05.083Z</atom:updated>
            <content:encoded><![CDATA[<h3>If you’ve worked with SwiftUI for a while, you’ve probably had this moment:</h3><p>Why is this view recreating?<br>Why is my API getting called again?<br>Why did my state reset?</p><p>Nothing looks wrong. But something clearly is.</p><p>In SDE-2 level interviews, SwiftUI questions are not about building UI. They are about whether you understand how SwiftUI actually works.</p><p>This is where many strong engineers get filtered out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zncTgGaLPtTQ1GvTzWGMOg.png" /></figure><h3>SwiftUI Views Are Not Views</h3><p>This is the first mindset shift.</p><p>A SwiftUI View is:</p><ul><li>A struct</li><li>A description of UI</li><li>Cheap to create</li><li>Recreated frequently</li></ul><pre>struct ProfileView: View {<br>    var body: some View {<br>        Text(&quot;Hello&quot;)<br>    }<br>}</pre><p>This is not the screen. It is a blueprint.</p><p>The actual UI is managed internally by the system.</p><p>A simple line that works well in interviews:</p><p>Views are disposable. State is not.</p><h3>Body Is Just a Function</h3><p>UIKit gives you lifecycle methods. SwiftUI does not.</p><p>There is no viewDidLoad or viewWillAppear.</p><p>Instead:</p><pre>var body: some View {<br>    Text(name)<br>}</pre><p>Body is just a function of state.</p><p>When state changes, body runs again.</p><p>Not once. Not predictably. Many times.</p><h3>Why You Should Not Put Logic Inside body</h3><p>This is one of the most common mistakes.</p><pre>var body: some View {<br>    fetchData()<br>    return Text(&quot;Hello&quot;)<br>}</pre><p>This will trigger multiple API calls because body can be evaluated many times.</p><p>Interviewers love this trap.</p><p>Correct takeaway:</p><p>Body is for describing UI. Not for side effects.</p><h3>State Drives Everything</h3><p>SwiftUI is state driven.</p><p>If the UI is wrong, your state is wrong. Not the framework.</p><h3>Property Wrappers That Actually Matter</h3><p>Most people memorize definitions. That is not enough.</p><p>You need to understand ownership.</p><h3>@State</h3><ul><li>Local to the view</li><li>Owned by the view</li><li>Value type</li></ul><h3>@StateObject</h3><ul><li>View owns the object</li><li>Created once</li><li>Survives view reloads</li></ul><pre>@StateObject var vm = ViewModel()</pre><h3>@ObservedObject</h3><ul><li>Injected dependency</li><li>Not owned by the view</li></ul><h3>@EnvironmentObject</h3><ul><li>Shared across the app</li><li>Global state</li></ul><h3>The @StateObject vs @ObservedObject Trap</h3><p>This comes up constantly in interviews.</p><pre>@ObservedObject var vm = ViewModel()</pre><p>This looks fine. It is not.</p><p>The ViewModel will be recreated every time the view reloads.</p><p>Correct approach:</p><p>If the view creates it, use StateObject.<br>If it is injected, use ObservedObject.</p><h3>Why Views Recreate</h3><p>SwiftUI rebuilds views based on changes.</p><p>Triggers include:</p><ul><li>State updates</li><li>Parent updates</li><li>Navigation changes</li><li>Environment changes</li></ul><p>Example:</p><pre>struct Parent: View {<br>    @State var count = 0</pre><pre>    var body: some View {<br>        ChildView()<br>    }<br>}</pre><p>Every time count changes, ChildView is recreated.</p><p>Even if ChildView does not use count.</p><h3>Identity Is Everything</h3><p>This is where things get interesting.</p><p>SwiftUI uses identity to decide:</p><ul><li>Whether to reuse a view</li><li>Whether to reset state</li><li>Whether to trigger lifecycle events</li></ul><h3>Lists and Identity</h3><pre>List(items, id: \.id) { item in<br>    Row(item: item)<br>}</pre><p>If the id changes:</p><ul><li>Views reset</li><li>State disappears</li><li>onAppear fires again</li></ul><h3>Common Bug</h3><pre>id: \.self</pre><p>This breaks when data changes.</p><p>Result:</p><ul><li>Flickering</li><li>State resets</li><li>Unexpected reloads</li></ul><h3>Side Effects Done Right</h3><p>SwiftUI separates rendering from side effects.</p><p>Use the right hooks.</p><h3>onAppear</h3><pre>.onAppear {<br>    loadData()<br>}</pre><h3>task</h3><pre>.task {<br>    await loadData()<br>}</pre><p>task is preferred for async work.</p><h3>Interview Follow Up</h3><p>What is the difference between onAppear and task?</p><p>A strong answer:</p><p>task supports async await and cancellation.<br>onAppear does not.</p><h3>Navigation Problems</h3><p>A common real world issue.</p><p>You push a screen. Go back. Push again.</p><p>State is gone. ViewModel is reset.</p><h3>Why This Happens</h3><ul><li>View identity changes</li><li>Object ownership is incorrect</li><li>ViewModel not retained properly</li></ul><h3>Fix</h3><ul><li>Use StateObject at the correct level</li><li>Maintain stable identity</li><li>Avoid creating objects inside frequently rebuilt views</li></ul><h3>Lists Are Not ScrollViews</h3><p>SwiftUI List:</p><ul><li>Lazy</li><li>Diff driven</li><li>Reuses cells</li></ul><p>Interviewers often ask:</p><p>Why does onAppear fire multiple times in a list?</p><p>Because rows are reused and recreated based on visibility.</p><h3>Common Mistake</h3><pre>struct Row: View {<br>    @State var isLiked = false<br>}</pre><p>If identity changes, state resets.</p><h3>Performance Pitfalls</h3><p>SwiftUI performance issues are subtle.</p><h3>Heavy Work Inside body</h3><pre>var body: some View {<br>    let result = heavyCalculation()<br>    return Text(&quot;\(result)&quot;)<br>}</pre><p>This runs every time body is evaluated.</p><h3>Too Many State Updates</h3><p>Frequent updates trigger re-renders.</p><h3>Wrong Identity</h3><p>Leads to unnecessary rebuilds.</p><h3>Large View Hierarchies</h3><p>Harder for SwiftUI to diff efficiently.</p><h3>When SwiftUI Is Not Enough</h3><p>This is a strong interview differentiator.</p><p>SwiftUI struggles with:</p><ul><li>Complex navigation flows</li><li>Fine control over lifecycle</li><li>Advanced animations</li><li>Deep UIKit integrations</li></ul><p>Strong candidates mention hybrid approaches.</p><h3>What Interviewers Actually Evaluate</h3><p>They are not checking syntax.</p><p>They want to know:</p><ul><li>Do you understand how SwiftUI thinks</li><li>Can you reason about state and identity</li><li>Can you debug unexpected behavior</li><li>Can you make correct architectural decisions</li></ul><h3>Final Thought</h3><p>SwiftUI feels simple until it does not. Most issues that look random are not random at all.</p><p>They come from:</p><ul><li>Wrong state ownership</li><li>Broken identity</li><li>Side effects in the wrong place</li></ul><p>Anyone can build a screen.</p><p>Fewer engineers can explain:</p><p>Why a view recreated<br>Why state reset<br>Why an API fired twice<br>How to structure state correctly</p><p>That is the SDE-2 bar.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71630303b04c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Management & ARC — What Senior Interviewers Actually Probe]]></title>
            <link>https://sejallkhanna.medium.com/memory-management-arc-what-senior-interviewers-actually-probe-543f63d0dab3?source=rss-f9615d0bfa9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/543f63d0dab3</guid>
            <dc:creator><![CDATA[Sejal Khanna]]></dc:creator>
            <pubDate>Wed, 18 Mar 2026 08:30:43 GMT</pubDate>
            <atom:updated>2026-03-18T08:30:43.729Z</atom:updated>
            <content:encoded><![CDATA[<h4>If concurrency questions test whether you can build correct systems under pressure, memory questions test something more uncomfortable:</h4><blockquote>Whether your code will quietly degrade, leak, slow down, and eventually get killed in production.</blockquote><p>In several senior iOS interview loops (including with large product companies), memory management questions weren’t theoretical. They were framed like incident retrospectives.</p><p>“App memory keeps growing after navigating back and forth — what do you do?”<br>“Why does this not crash immediately?”<br>“Where would you look first?”</p><p>This chapter covers the memory topics that repeatedly surface in SDE-2 interviews — not as trivia, but as judgment tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*selHv_8iSn8q3BVHkdIVUQ.png" /></figure><h3>ARC — Not Magic, Just Accounting</h3><p>Swift uses Automatic Reference Counting (ARC), which is essentially deterministic memory management based on reference counts.</p><p>For <strong>class instances</strong> only.</p><p>Not structs. Not enums. Not pure value types.</p><p>Every strong reference increments a count. When the count reaches zero, the object is deallocated immediately.</p><p>No background GC sweep. No unpredictability.</p><p>Interviewers often probe whether you understand this determinism.</p><p>A useful mental model:</p><blockquote>ARC frees memory when ownership ends, not when memory pressure happens.</blockquote><h3>Strong, Weak, Unowned — Ownership Semantics</h3><p>Most candidates can define these. Fewer can explain when each is correct.</p><h3>Strong (default)</h3><p>Keeps the object alive.</p><pre>var user: User?</pre><pre>Use when you own the object or need it guaranteed to exist.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*33nDGZMt5vueMBEcJdtj6A.png" /></figure><h3>Weak</h3><ul><li>Does not increase reference count</li><li>Automatically becomes nil when object deallocates</li><li>Must be optional</li></ul><p>Typical use: breaking retain cycles.</p><pre>weak var delegate: SomeDelegate?</pre><h3>Unowned</h3><ul><li>Does not increase reference count</li><li>Assumes the object will always exist</li><li>Non-optional</li><li>Crashes if accessed after deallocation</li><li>Use only when lifetimes are tightly coupled.</li></ul><p>Example: child referencing parent.</p><pre>unowned let parent: Parent</pre><h3>Interview Favorite</h3><p><strong>When is weak incorrect?</strong></p><p>Answer:</p><p>When the referenced object is required for correct execution. Making it weak can introduce silent logic failures because it may become nil unexpectedly.</p><p>Weak prevents leaks. It does not guarantee correctness.</p><h3>Retain Cycles — The Real Production Problem</h3><p>ARC cannot break cycles automatically.</p><p>If two objects strongly reference each other, their reference counts never reach zero.</p><p>Classic example:</p><pre>class A {<br>    var b: B?<br>}</pre><pre>class B {<br>    var a: A?<br>}</pre><p>Neither deallocates.</p><h3>Closures Capturing self</h3><p>This is where most real leaks originate.</p><pre>class ViewModel {<br>    func load() {<br>        service.fetch { result in<br>            self.handle(result)<br>        }<br>    }<br>}</pre><p>If the service retains the closure and the closure retains self, you have a cycle.</p><p>Typical fix:</p><pre>service.fetch { [weak self] result in<br>    self?.handle(result)<br>}</pre><h3>But Here’s the SDE-2 Insight</h3><p>Blindly using [weak self] is not always correct.</p><p>Interviewers increasingly ask:</p><blockquote><em>When would you NOT use weak self?</em></blockquote><p>Examples:</p><ul><li>When the closure must complete work for correctness</li><li>When losing self mid-operation is a bug</li><li>Short-lived closures that don’t escape</li></ul><p>A strong answer mentions intentional ownership decisions, not cargo-cult patterns.</p><h3>High-Risk Retain Cycle Sources in Real Apps</h3><p>Senior interviews often move beyond closures.</p><h3>Delegates</h3><p>Delegates should almost always be weak.</p><p>Otherwise:</p><p>View → ViewController → Delegate → View</p><p>Cycle.</p><h3>Timers</h3><p>Timer retains its target.</p><p>If the target also retains the timer, neither deallocates.</p><h3>CADisplayLink</h3><p>Same issue as timers, but harder to notice because it runs continuously.</p><h3>NotificationCenter Observers</h3><p>Block-based observers retain the closure, which retains captured objects.</p><h3>Combine Pipelines</h3><p>Subscriptions retained by objects often retain closures that capture those objects.</p><h3>Async Tasks</h3><p>Structured concurrency reduces risk, but tasks can still retain captured references.</p><h3>Why Leaks Don’t Crash Immediately</h3><p>A question that came up in multiple interviews.</p><p>Leaks are insidious because:</p><ul><li>Memory grows gradually</li><li>System doesn’t free leaked objects</li><li>App still functions initially</li><li>Eventually memory pressure kills the app</li></ul><p>Often manifests as:</p><ul><li>Sluggish performance</li><li>Background termination</li><li>Random relaunches</li><li>Jetsam kills without crash logs</li></ul><h3>Real Production Scenario</h3><p>Navigate repeatedly between two screens.</p><p>Each time:</p><ul><li>New view controller allocated</li><li>Old one never deallocated</li><li>Memory graph slowly grows</li></ul><p>Users report:</p><p>“The app becomes slow after using it for a while.”</p><h3>Debugging Workflow — What Senior Engineers Do</h3><p>This is where candidates differentiate themselves.</p><h3>Step 1 — Confirm Leak Pattern</h3><p>Reproduce navigation loop. Watch memory usage.</p><h3>Step 2 — Memory Graph Debugger</h3><p>Pause app → inspect object graph.</p><p>Look for:</p><ul><li>Retained view controllers</li><li>Unexpected ownership chains</li><li>Closure capture paths</li></ul><h3>Step 3 — Instruments (Leaks + Allocations)</h3><p>Use when leak is not obvious. Allocations shows memory growth over time. Leaks identifies objects that are never released.</p><h3>Step 4 — Zombies (for crashes)</h3><p>Helps detect messaging deallocated objects.</p><h3>Autorelease Pools — (Yes, Still Relevant)</h3><p>Swift interacts with Objective-C runtime and Foundation.<br>Temporary objects may accumulate in autorelease pools.</p><p>Important in tight loops or background processing.</p><pre>for item in hugeDataset {<br>    autoreleasepool {<br>        process(item)<br>    }<br>}</pre><p>Without this, memory spikes until the pool drains. Interviewers sometimes use this to test deeper runtime knowledge.</p><h3>Value Types Are Not a Free Pass</h3><p>Structs don’t participate in ARC, but they can still cause memory issues.</p><p>Large value types copied frequently can:</p><ul><li>Increase memory footprint</li><li>Cause performance degradation</li><li>Trigger copy-on-write allocations</li></ul><p>Example: large arrays passed across threads and mutated.</p><h3>Copy-on-Write — Performance Trade-offs</h3><p>Swift collections share storage until mutated.</p><p>Efficient in most cases. But heavy mutation patterns can create many copies.</p><p>Senior insight:</p><blockquote><strong>Value semantics improve safety but not always memory efficiency.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5UYcqlcaGyMoC1FOqlsOg.png" /></figure><h3>Caches — The Silent Memory Consumer</h3><p>Real systems rely heavily on caching.</p><p>Problems arise when:</p><ul><li>Cache never evicts</li><li>Memory warnings ignored</li><li>Large objects stored indefinitely</li></ul><p>Interviewers may ask:</p><blockquote>How would you design a memory-safe cache?</blockquote><p>Expected mentions:</p><ul><li>Size limits</li><li>Eviction policies</li><li>Memory pressure handling</li><li>NSCache behavior</li></ul><h3>ARC and Performance</h3><p>Reference counting itself has overhead.</p><p>High object churn can:</p><ul><li>Increase CPU usage</li><li>Cause allocation pressure</li><li>Trigger frequent retain/release operations</li></ul><p>This matters in hot paths like scrolling or rendering.</p><h3>Can ARC Cause Crashes?</h3><p>Not directly, but misuse can.</p><p>Examples:<br>Over-releasing via unsafe APIs<br>Accessing unowned reference after deallocation<br>Logic errors from weak references becoming nil</p><h3>What SDE-2 Interviewers Actually Evaluate</h3><p>Memory questions aren’t about definitions. They’re about whether you’ve dealt with real failures.</p><p>Strong signals include:</p><ul><li>Understanding ownership semantics</li><li>Ability to reason about lifetimes</li><li>Practical debugging approach</li><li>Awareness of performance trade-offs</li><li>Production experience</li></ul><h3>Final Thought</h3><p><strong>Memory bugs rarely fail loudly. They accumulate quietly, degrade performance, and surface only after real usage patterns emerge.</strong></p><p>Anyone can explain ARC. Fewer engineers can:</p><ul><li>Diagnose leaks in complex graphs</li><li>Choose the correct ownership model</li><li>Prevent retain cycles without breaking logic</li><li>Design memory-stable systems at scale</li></ul><p>That’s the SDE-2 bar.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=543f63d0dab3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency for iOS SDE-2 Interviews — The Stuff You’re Actually Judged On]]></title>
            <link>https://sejallkhanna.medium.com/concurrency-for-ios-sde-2-interviews-the-stuff-youre-actually-judged-on-22798d5edf50?source=rss-f9615d0bfa9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/22798d5edf50</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[sde-interview]]></category>
            <category><![CDATA[product-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Sejal Khanna]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 13:46:07 GMT</pubDate>
            <atom:updated>2026-03-16T13:47:34.680Z</atom:updated>
            <content:encoded><![CDATA[<h3>Concurrency for iOS SDE-2 InterviewsThe Stuff You’re Actually Judged On :)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rrM20h0SkYiKovy4EgXICA.png" /></figure><h4>If you’re preparing for SDE-2 iOS interviews, “Do you know GCD?” is not the question.</h4><p>The real question is:</p><blockquote><strong>Can you design, reason about, and debug concurrent systems without accidentally freezing the app, corrupting data, or melting battery life?</strong></blockquote><p>Over the past few interview cycles (including some very pointed ones from large product companies), I noticed that concurrency questions aren’t about syntax. They’re about judgment.</p><p>This chapter covers <strong>everything that tends to come up around concurrency- </strong>concepts, traps, real production scenarios, and the kind of answers that signal senior-leaning thinking.</p><h3>Concurrency vs Parallelism (Yes, They Still Ask This)</h3><p>At least one interviewer will start here to calibrate your fundamentals.</p><p><strong>Concurrency</strong><br>Managing multiple tasks at once. Tasks make progress by interleaving.</p><p><strong>Parallelism</strong><br>Executing multiple tasks at the exact same time on different cores.</p><p>iOS apps mostly care about concurrency for responsiveness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*EW8TJe4Mw3iZJ34wmizkQg.png" /></figure><p><strong>Example</strong></p><p>Concurrency:</p><ul><li>User scrolls a feed</li><li>Images download</li><li>Taps are handled</li><li>UI updates</li></ul><p>Parallelism:</p><ul><li>Image filters applied on multiple cores</li><li>Video processing</li><li>ML inference</li></ul><p>A good one-liner:</p><blockquote><strong>Concurrency is about responsiveness. Parallelism is about throughput.</strong></blockquote><h3>Sync vs Async — What It Actually Means</h3><p>This distinction trips people because it sounds like “parallel vs serial.” It isn’t.</p><p><strong>Sync vs async affects the calling thread.</strong></p><p>syncasyncBlocks the callerReturns immediatelyWaits for completionExecutes later</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*a-lg-Pb3nJzD3ziqDTSBZg.png" /></figure><p>Example:</p><pre>let queue = DispatchQueue(label: &quot;test&quot;)</pre><pre>print(&quot;1&quot;)</pre><pre>queue.sync {<br>    print(&quot;2&quot;)<br>}</pre><pre>print(&quot;3&quot;)</pre><p>Output: 1 2 3</p><pre>print(&quot;1&quot;)</pre><pre>queue.async {<br>    print(&quot;2&quot;)<br>}</pre><pre>print(&quot;3&quot;)</pre><p>Output: usually 1 3 2</p><h3>Real Interview Angle</h3><p>A common follow-up:</p><blockquote><strong><em>What happens if you call a long sync task on the main thread?</em></strong></blockquote><p><strong><em>Correct answer: you freeze the UI. The watchdog may kill your app if it’s bad enough.</em></strong></p><h3>Serial vs Concurrent Queues</h3><p>Another foundational axis.</p><h3>Serial Queue</h3><ul><li>One task at a time</li><li>Order guaranteed</li><li>Often used for protecting shared state</li></ul><pre>let serial = DispatchQueue(label: &quot;serial&quot;)</pre><h3>Concurrent Queue</h3><ul><li>Multiple tasks may run simultaneously</li><li>Order not guaranteed</li></ul><pre>let concurrent = DispatchQueue(<br>    label: &quot;con&quot;,<br>    attributes: .concurrent<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*WK2ROABtFdWrS2GFI0NQ9g.png" /></figure><h3>Real Production Uses</h3><p>Serial queue:</p><ul><li>Writing to disk</li><li>Database updates</li><li>Logging pipelines</li></ul><p>Concurrent queue:</p><ul><li>Network requests</li><li>Image processing</li><li>Background computation</li></ul><h3>Deadlocks — The Interview Classic</h3><p>One company I spoke with drilled into this for nearly 20 minutes.</p><p>The textbook case</p><p>Calling sync on the same serial queue.</p><pre>let queue = DispatchQueue(label: &quot;q&quot;)</pre><pre>queue.sync {<br>    queue.sync {<br>        print(&quot;Deadlock&quot;)<br>    }<br>}</pre><h3>Why it deadlocks</h3><ul><li>Outer block holds the queue</li><li>Inner sync waits for the queue</li><li>Queue can’t progress until outer finishes</li><li>Circular wait</li></ul><p>Rule worth memorizing:</p><blockquote><strong>Never call sync on the same serial queue.</strong></blockquote><h3>The symptom: app freeze with no crash.</h3><h3>Race Conditions — Where Bugs Get Interesting</h3><p>A race condition occurs when multiple threads access shared mutable state without synchronization.</p><p>Classic demo:</p><pre>var counter = 0</pre><pre>DispatchQueue.concurrentPerform(iterations: 1000) { _ in<br>    counter += 1<br>}</pre><p>Expected: 1000<br>Actual: unpredictable</p><h3>Real iOS Scenarios</h3><ul><li>Analytics counters</li><li>In-memory caches</li><li>Token refresh logic</li><li>Inventory or balance calculations</li><li>Feature flag updates</li></ul><p>These bugs often pass testing and fail in production under load.</p><h3>Making Code Thread-Safe (What Interviewers Care About Most)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*_TvN9AiuqzI1UFOS14rH2g.png" /></figure><h3>1) Serial Queue Isolation</h3><p>Simple and extremely common.</p><pre>class SafeCounter {<br>    private var value = 0<br>    private let queue = DispatchQueue(label: &quot;counter&quot;)</pre><pre>    func increment() {<br>        queue.sync { value += 1 }<br>    }</pre><pre>    func get() -&gt; Int {<br>        queue.sync { value }<br>    }<br>}</pre><p>Safe because only one task touches the state at a time.</p><h3>2) Concurrent Queue + Barrier (Reader-Writer Pattern)</h3><p>This is a favorite SDE-2 question.</p><p>Allows:</p><ul><li>Many concurrent reads</li><li>Exclusive writes</li></ul><pre>class Cache {<br>    private var data: [String: Int] = [:]<br>    private let queue = DispatchQueue(<br>        label: &quot;cache&quot;,<br>        attributes: .concurrent<br>    )</pre><pre>    func get(_ key: String) -&gt; Int? {<br>        queue.sync { data[key] }<br>    }</pre><pre>    func set(_ key: String, value: Int) {<br>        queue.async(flags: .barrier) {<br>            self.data[key] = value<br>        }<br>    }<br>}</pre><p>Interviewers like this pattern because it balances safety and performance.</p><h3>3) Locks (Know Them, Don’t Overuse Them)</h3><p>Examples:</p><ul><li>NSLock</li><li>pthread mutex</li><li>RecursiveLock</li></ul><p>Modern Swift code tends to prefer queues or actors, but locks still exist in legacy systems.</p><h3>Semaphores — Controlled Concurrency</h3><p>Used to limit access to resources.</p><p>Example: only allow two API calls at a time.</p><pre>let semaphore = DispatchSemaphore(value: 2)</pre><pre>for task in tasks {<br>    DispatchQueue.global().async {<br>        semaphore.wait()</pre><pre>        performNetworkCall()</pre><pre>        semaphore.signal()<br>    }<br>}</pre><h3>Real Scenarios</h3><ul><li>Rate limiting</li><li>Resource pools</li><li>File access control</li><li>Preventing server overload</li></ul><p>One interviewer explicitly asked when semaphores are appropriate versus a queue. The key distinction is that semaphores control concurrency count, not execution order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3Hl4i3XW9CBUxNYkmZeNQ.png" /></figure><h3>Dispatch Groups — Waiting for Multiple Tasks</h3><p>Useful when you need to know when several async operations finish.</p><pre>let group = DispatchGroup()</pre><pre>for url in urls {<br>    group.enter()</pre><pre>    fetch(url) {<br>        group.leave()<br>    }<br>}</pre><pre>group.notify(queue: .main) {<br>    print(&quot;All done&quot;)<br>}</pre><h3>Real Use Cases</h3><ul><li>Loading a dashboard from multiple APIs</li><li>Batch image downloads</li><li>Syncing offline data</li></ul><h3>Quality of Service (QoS)</h3><p>QoS tells the system how important the work is.</p><p>From highest to lowest:</p><h3>userInteractive</h3><p>Immediate UI work<br>Animations, gestures</p><h3>userInitiated</h3><p>User is waiting for results<br>Loading next screen</p><h3>utility</h3><p>Long-running work<br>Downloads, processing</p><h3>background</h3><p>Not user-visible</p><p>QoS influences:</p><ul><li>CPU priority</li><li>Scheduling</li><li>Energy usage</li></ul><p>Good candidates mention battery impact. Great ones mention that overusing high QoS harms system responsiveness.</p><h3>OperationQueue vs GCD</h3><p>A company once asked:</p><blockquote><strong><em>Why would you use OperationQueue in 2026?</em></strong></blockquote><p><strong><em>Because it offers higher-level features:</em></strong></p><ul><li><strong><em>Dependencies</em></strong></li><li><strong><em>Cancellation</em></strong></li><li><strong><em>Progress tracking</em></strong></li><li><strong><em>Concurrency limits</em></strong></li></ul><p>Example dependency:</p><pre>let op1 = BlockOperation { print(&quot;1&quot;) }<br>let op2 = BlockOperation { print(&quot;2&quot;) }</pre><pre>op2.addDependency(op1)</pre><pre>queue.addOperations([op1, op2], waitUntilFinished: false)</pre><p>Use it when orchestration matters more than raw performance.</p><h3>Structured Concurrency (async/await)</h3><p>Modern Swift concurrency is heavily tested now.</p><p>Benefits:</p><ul><li>Linear readable code</li><li>Built-in cancellation</li><li>Error handling with try</li><li>Integration with actors</li></ul><p>Example:</p><pre>func load() async throws -&gt; Data {<br>    let (data, _) = try await URLSession.shared.data(from: url)<br>    return data<br>}</pre><h3>Actors — Built-In Thread Safety</h3><p>Actors isolate mutable state.</p><pre>actor BankAccount {<br>    private var balance = 0</pre><pre>    func deposit(_ amount: Int) {<br>        balance += amount<br>    }</pre><pre>    func getBalance() -&gt; Int {<br>        balance<br>    }<br>}</pre><p>Why interviewers like actors:</p><ul><li>No manual locking</li><li>Compiler enforcement</li><li>Eliminates data races by design</li></ul><p>Typical use cases:</p><ul><li>Shared models</li><li>Token managers</li><li>Financial logic</li><li>Global app state</li></ul><h3>UI Must Stay on the Main Thread</h3><p>UIKit and SwiftUI rendering are main-thread bound.</p><p>Violations cause:</p><ul><li>Crashes</li><li>Glitches</li><li>Undefined behavior</li></ul><p>Correct pattern:</p><pre>DispatchQueue.main.async {<br>    label.text = &quot;Done&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BG0pDl5kmOrqT-za3nu1vg.png" /></figure><h3>What SDE-2 Interviewers Actually Evaluate</h3><p>Not whether you memorized APIs. They look for:</p><ul><li>Ability to reason about failures</li><li>Trade-offs between approaches</li><li>Production awareness</li><li>Debugging intuition</li><li>Performance considerations</li></ul><p>A strong candidate answers not just “how,” but “when and why.”</p><h3>Final Thought</h3><p><strong><em>Concurrency questions are rarely about writing code on a whiteboard. They’re about demonstrating that you can build systems that behave correctly under stress.</em></strong></p><p><strong><em>Anyone can spin up a background queue.</em></strong></p><p><strong><em>Fewer engineers can explain:</em></strong></p><ul><li><strong><em>When a barrier is appropriate</em></strong></li><li><strong><em>Why a deadlock happened</em></strong></li><li><strong><em>How to prevent race conditions without killing performance</em></strong></li><li><strong><em>Which tool to use for a given scenario</em></strong></li></ul><p><strong><em>That’s the SDE-2 bar.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22798d5edf50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My journey so far]]></title>
            <link>https://sejallkhanna.medium.com/my-journey-so-far-ae75bfd165b4?source=rss-f9615d0bfa9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae75bfd165b4</guid>
            <category><![CDATA[growth]]></category>
            <category><![CDATA[careers]]></category>
            <dc:creator><![CDATA[Sejal Khanna]]></dc:creator>
            <pubDate>Fri, 24 Dec 2021 12:34:38 GMT</pubDate>
            <atom:updated>2021-12-24T12:34:38.954Z</atom:updated>
            <content:encoded><![CDATA[<p>I vividly remember the first I had heard of <a href="https://medium.com/u/3bb4720de074">OneBanc Technologies Pvt. Ltd.</a>was from a senior of mine who had interviewed for the same role as me back in June. It had been a few months already and I was working with different organizations as an intern on numerous domains. Even though I was working as an intern with some really talented folks, I was unable to find the satisfaction of excelling and always felt that there was a lot more I could learn.</p><p>To me working for a startup was more important as I was looking for a platform where I could learn and not just about my field but the holistic approach of a product. I remember being interviewed by <a href="https://www.linkedin.com/in/ACoAACdBLtYBFz8vNjXLNLrjyrnlwPpMQybWw-8">Maninder Singh </a>, who made sure it wasn’t as easy as I had hoped the interview to be. By the end of it, I knew what kind of level of work would be expected from me.</p><p>My interview with <a href="https://www.linkedin.com/in/ACoAAABFYwoB_J2IGWkG7Xugeth0Q38_wxHYRXQ">Vibhore Goyal</a> was more of an experience in itself, from the first time I met him, he seemed very approachable. I have had lesser interactions than what I would like to, but even in those brief sessions, I have managed to learn so much about his perspective and how one should approach problems.</p><p>As I started working at OneBanc, initially it was a difficult shift considering I had been home for almost 2 years and here I was working at an office which demanded enormous energy since Day 1. From the very first day, the entire team made me feel like home.</p><p>One month down the line, I started having apprehensions as I was doubting myself. I was unable to comprehend if I was even fit for a technical role or that if I would be able to contribute well at work. There were a few sudden shifts in the team around the same time, which made things even more unsettling for me. I shared this with <a href="https://www.linkedin.com/in/ACoAAAFMmEUBiLEZOULSDNv-tfzfIIC1Nu-dqAw">Ishita Mehta</a> and a few others and they all helped me understand how my hard work and determination would help me overcome these fears.</p><p>At OneBanc — I have had the amazing chance to interact with a team of people that comes from different professional backgrounds. My interactions with them help me learn beyond my role and adds to my personal growth. 📈</p><p>As an avid problem-solver, I was very fervent by the idea presented by the OneBanc.</p><p>I think irrespective of what people consider the organisations culture to be, all I have witnessed is that every person in the team has this constant zeal, a constant drive to make the vision of OneBanc a reality. I see the belief we all share that makes it easier to lend all our focus and determination to this endeavour.</p><p>After over 4 months at <a href="https://www.linkedin.com/company/onebanc/">OneBanc Technologies Pvt. Ltd.</a>, I can safely claim that I have never felt like I am an Intern, rather found the best learning curve I had hoped for. ☺️</p><p><a href="https://www.linkedin.com/feed/hashtag/?keywords=demandmore&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A6879346828349890560">#DemandMore</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=chaseyourdreams&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A6879346828349890560">#chaseyourdreams</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae75bfd165b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>