<?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 Paresh J Thakor on Medium]]></title>
        <description><![CDATA[Stories by Paresh J Thakor on Medium]]></description>
        <link>https://medium.com/@mobihunterz?source=rss-df01e0532538------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H-lyK4DIUCqQ6fMmwYQXYA.jpeg</url>
            <title>Stories by Paresh J Thakor on Medium</title>
            <link>https://medium.com/@mobihunterz?source=rss-df01e0532538------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 00:35:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mobihunterz/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[Swift’s indirect Keyword: Recursive Enums and Memory Management]]></title>
            <link>https://medium.com/@mobihunterz/swifts-indirect-keyword-recursive-enums-and-memory-management-3bd0b88c171a?source=rss-df01e0532538------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bd0b88c171a</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Paresh J Thakor]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 18:32:11 GMT</pubDate>
            <atom:updated>2026-10-03T18:32:11.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFeECVpUA3Wi8ifYsEMMqQ.jpeg" /></figure><p>When building data structures like trees, linked lists or expression parsers in Swift, you may encounter a compiler error that reads: <strong>“Value type ‘X’ has infinite size.” </strong>Swift provides the indirect keyword to resolve this.</p><p>In this article, we will explore</p><ul><li>what the indirect keyword does</li><li>walk through the example</li><li>dive into how it transforms memory layout, ARC (Automatic Reference Counting) and access mechanics</li></ul><h3>The Problem: Infinite Size in Value Types</h3><p>Swift enum are <strong>value types</strong>. By default, value types are <strong>stored inline on the stack</strong>, meaning the compiler must know the exact memory footprint of an enum at compile time.</p><p>Consider a binary tree structure defined recursively using an enum:</p><pre>// ❌ Compiler Error: Value type enum &#39;Node&#39; can&#39;t have recursion - infinite size<br>enum Node {<br>    case leaf(Value: Int)<br>    case node(left: Node, right: Node) <br>}</pre><p>As node contains two instances of Node, calculating the size:</p><blockquote><strong>Size(Node) = Size(Int) </strong>+<strong> 2 </strong>x<strong> Size(Node)</strong></blockquote><p>How confusing is it? It creates a recursive definition of infinite size. This can’t be allocated on the stack as the compiler can’t guess its proper size.</p><h3>The Solution: The indirect Keyword</h3><p>The indirect keyword tells the Swift compiler to introduce a layer of indirection by boxing the enum payload on the <strong>heap </strong>via a reference, rather than storing it directly inline.</p><h3>The Example</h3><p>You can apply indirect directly to individual cases or to the entire enum declaration if multiple cases need indirection.</p><pre>struct Exercise {<br>    let name: String<br>    let targetReps: Int<br>    let durationSeconds: TimeInterval<br>}<br><br>indirect enum WorkoutBlock {<br>    // Single exercise<br>    case single(Exercise)<br>    <br>    // Composite block (e.g., Superset, AMRAP circuit, or Rest sequence)<br>    case circuit(<br>        name: String,<br>        rounds: Int,<br>        blocks: [WorkoutBlock]<br>    )<br>}<br><br>// MARK: - Usage<br>let pushups = WorkoutBlock.single(Exercise(name: &quot;Push-ups&quot;, targetReps: 15, durationSeconds: 45))<br>let plank = WorkoutBlock.single(Exercise(name: &quot;Plank&quot;, targetReps: 1, durationSeconds: 60))<br><br>// Core Superset (2 rounds of pushups + plank)<br>let coreSuperset = WorkoutBlock.circuit(<br>    name: &quot;Core Superset&quot;,<br>    rounds: 2,<br>    blocks: [pushups, plank]<br>)<br><br>// Main Conditioning Circuit containing the superset<br>let fullWorkout = WorkoutBlock.circuit(<br>    name: &quot;Full Body Blast&quot;,<br>    rounds: 2,<br>    blocks: [coreSuperset]<br>)</pre><h3>How Storage and Access Changes Under the Hood</h3><h3>1. Storage Layout (Stack vs. Heap)</h3><ul><li><strong>Without </strong><strong>indirect:</strong> Values reside purely on the stack or inline within their parent structure.</li><li><strong>With </strong><strong>indirect:</strong> Swift allocates a small managed reference box (SwiftObject) on the <strong>heap</strong> for the indirect case&#39;s payload. The enum instance on the stack only stores a pointer to that heap allocation (plus the enum tag byte to identify the case).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-_2k614UHwJjfzJF3M5mQ.png" /></figure><h3>2. Access Mechanics</h3><p>Accessing an indirect enum case requires <strong>pointer dereferencing</strong>:</p><ol><li>Swift checks the enum tag.</li><li>If the case is indirect, it fetches the memory address from the stack.</li><li>It dereferences the pointer to read or write the heap-allocated value.</li></ol><p>While pointer <strong>dereferencing adds a minuscule runtime overhead</strong> (a cache miss is possible), it enables dynamic, unbounded recursive data structures.</p><h3>Impact on Automatic Reference Counting (ARC)</h3><p>Because indirect moves the payload to a managed heap box, <strong>it introduces reference counting overhead to value types</strong>:</p><ul><li><strong>Reference Counting:</strong> Creating, copying or passing an indirect enum case increments or decrements the reference count of the underlying heap box.</li><li><strong>Copy-on-Write (CoW):</strong> Value semantics are maintained. When you mutate an indirect enum instance shared across multiple variables, Swift executes a Copy-on-Write step—allocating a new heap box for the mutated copy to keep instances independent.</li></ul><h3>Restrictions and Key Rules</h3><ul><li><strong>Only Applicable to Enums:</strong> The indirect keyword can only be applied to enum declarations or specific enum cases. You cannot use it directly on struct properties (for recursive structs, wrap recursive properties in an enum or a class Box&lt;T&gt;).</li></ul><pre>struct Exercise {<br>    let name: String<br>    ...<br>    let nextExercise: Exercise?  // recursion - error<br>    let recommendations: [Exercise]? // recursion - works<br>}<br><br>// Solution:<br>// 1. use enum with indirect<br>indirect enum Exercise {<br>    case single<br>    case circuit<br>}<br><br>// 2. class wrapper<br>final class Box&lt;T&gt; {<br>    let value: T<br>    init(_ value: T) { self.value = value }<br>}<br><br>struct Exercise {<br>    let name: String<br>    ...<br>    let nextExercise: Box&lt;Exercise&gt;? // Recursive reference wrapped in the Box class<br>}</pre><ul><li><strong>Cannot apply to </strong><strong>rawRepresentable values directly:</strong> Raw-value enums (e.g., enum Code: String) cannot be indirectbecause their instances are backed by explicit primitive literal values.</li><li><strong>Reference Overhead:</strong> Do not use indirect casually on non-recursive cases, as it incurs heap allocation and ARC overhead where simple stack allocation would be more performant.</li></ul><h3>Key Take Aways:</h3><ul><li>Enums are value types that require a fixed size at compile time; direct recursion creates an infinite memory loop that causes a compiler error. indirect fixes the error.</li><li>indirect forces enum to be stored behind a fixed-size pointer on the heap which breaks the infinite size loop.</li><li>indirec can’t be applied to structs; require class Box or enum support.</li><li>Work on data models to avoid recursion if possible.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bd0b88c171a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous Teardown in Swift: async defer]]></title>
            <link>https://medium.com/@mobihunterz/asynchronous-teardown-in-swift-async-defer-d53aad61f05b?source=rss-df01e0532538------2</link>
            <guid isPermaLink="false">https://medium.com/p/d53aad61f05b</guid>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Paresh J Thakor]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 04:41:11 GMT</pubDate>
            <atom:updated>2026-08-06T04:41:11.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDDNOQuGFaHVW4KgJeMDDw.png" /></figure><p>If you have built iOS apps using Swift involving database transactions, temporary files or network locks, you have likely relied on defer to clean up resources.</p><p>defer guarantees that a block of code will run right before the current scope exits, regardless of whether the function finishes normally or throws an error.</p><p>Prior to <strong>Swift 6.4</strong>, Swift’s concurrency model had a subtle flaw when it came to asynchronous teardown.</p><p><strong>The Problem:</strong> defer blocks were strictly synchronous before Swift 6.4 and if your resource cleanup required an async call, such as rolling back a database transaction you couldn&#39;t use await directly inside defer. To work around this limitation, we usually opt for workarounds, which have significant drawbacks:</p><h4>The Unstructured Task — Race Condition Hazard</h4><p>The most common workaround was to wrap the async call inside a Task.</p><pre>func creditBonusRewards(to user: User, amount: Int) async throws {<br>    let transaction = await database.beginTransaction()<br>    <br>    defer {<br>        Task {<br>            // ⚠️ Danger: Unstructured concurrency!<br>            await transaction.rollbackIfNeeded() <br>        }<br>    }<br>    <br>    try await database.credit(user: user.id, points: amount)<br>    try await database.logLedger(userId: user.id, delta: amount)<br>    try await transaction.commit()<br>}</pre><p>Task { ... } creates an <strong>unstructured, detached concurrent task</strong>. When an error occurs:</p><ol><li>The function hits the defer block.</li><li>It executes the background Taskseparately.</li><li>The function exits immediately and returns (or throws) to the caller. Errors thrown from defer are completely goes silent.</li></ol><p>And the parent function is destroyed before rollbackIfNeeded() actually executes, the caller resumes execution while the database transaction is still open. If the caller immediately performs another database operation, it hits a <strong>race condition</strong>.</p><p><em>We need to handle the race condition with locking mechanisms and reference to </em><em>Task used for clean up.</em></p><h4>Manual do/catch Duplication</h4><p>Don’t use defer at all.</p><pre>func creditBonusRewards(to user: User, amount: Int) async throws {<br>    let transaction = await database.beginTransaction()<br>    <br>    do {<br>        try await database.credit(user: user.id, points: amount)<br>        try await database.logLedger(userId: user.id, delta: amount)<br>        try await transaction.commit()<br>    } catch {<br>        // Manual cleanup path<br>        await transaction.rollbackIfNeeded()<br>        throw error<br>    }<br>}</pre><p>If your function has early return statements, multiple guard clauses, or nested conditions, you must copy and paste await transaction.rollbackIfNeeded() at every single exit point. Miss one, and you leak a resource.</p><h4>Native async defer for Swift 6.4+</h4><p>When a function scope exits, Swift treats the exit point as a<strong> suspension point</strong>, guaranteeing that all asynchronous cleanup in defer is fully completed <strong>before</strong> control returns to the caller.</p><pre>func creditBonusRewards(to user: User, amount: Int) async throws {<br>    let transaction = await database.beginTransaction()<br>    var isCommitted = false<br><br>    defer {<br>        if !isCommitted {<br>            await transaction.rollbackIfNeeded()<br>        }<br>    }<br><br>    try await database.credit(user: user.id, points: amount)<br>    try await database.logLedger(userId: user.id, delta: amount)<br>    <br>    try await transaction.commit()<br>    isCommitted = true // Set flag AFTER commit succeeds<br>}</pre><h4>What was blocking async in defer?</h4><ul><li><strong>Synchronous stack unwinding:</strong> Deallocation of stack was synchronous only. Introducing such suspension point using async while stack-unwinding means to pause the destruction. This was a challenge in early Swift.</li><li><strong>Double throws of errors:</strong> Swift had no mechanism to handle a function throwing error and deferat the same time while using async.</li><li><strong>Suspension points on Exit:</strong> The Swift runtime had no mechanism to mark exit points as suspension points which is critical for defer.</li></ul><h4>Why it works now?</h4><ul><li><strong>Suspension points of Exit:</strong> Compiler is able to synthesize suspension points on exist containing async defer.</li><li><strong>Closure Inference and Scope Extension:</strong> When await is used inside defer, the compiler automatically inferes the defer block as async. The lifetime for all local variables and the block is extended until async operation completes.</li><li><strong>Reordering </strong><strong>async operations by LIFO:</strong> Chaining defers are arranged sequntially to complete their execution. If defer { await cleanupA() } is defined before defer { await cleanupB() }, the runtime rearranges the code and executes await cleanupB(); await cleanupA() before clearing the function memory.</li><li><strong>Isolation Inheritance and Cancellation Handling:</strong> async defer automatically inherits the actor isolation context of the enclosing function scope. This prevents unnecessary executor hops when interacting with actor-isolated properties during teardown. The defer execution continues on the same parent Task. As the defer execution continues on the same parent Task, if the task was cancelled, any await inside defer still runs under that cancelled context (which is why guarding critical operations like database rollbacks with withTaskCancellationShield remains important for fallible cleanup).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d53aad61f05b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Stock market Watchlist Screen — MVVM and Best Practices in SwiftUI/Swift]]></title>
            <link>https://medium.com/@mobihunterz/ios-stock-market-watchlist-screen-mvvm-and-best-practices-in-swiftui-swift-fb55c6111e09?source=rss-df01e0532538------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb55c6111e09</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Paresh J Thakor]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 23:33:19 GMT</pubDate>
            <atom:updated>2025-12-14T23:33:19.297Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS Stock market Watchlist Screen — MVVM and Best Practices in SwiftUI/Swift</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Qmn-Yp0GC3fA-DAJAVONQA.gif" /></figure><p>I am fond of Stock apps and feel impressed how some of the apps refresh prices every few seconds, like, sparking lights on New Year’s Eve.</p><p>I always think on best practices to implement such listing rather than naive way of reloading whole screen in earlier years of development. Architectures improved = way of implementation improved.</p><p><strong>Functional Requirements</strong>:</p><ul><li>⏱️ <strong>Price updates</strong> every few seconds (consider every 15 seconds)</li><li>👀 Price updates only for <strong>on-screen cells/rows</strong> (stop updates for off-screen cells/rows which brings unnecessary load)</li><li>🎯 Only <strong>redraw the Price label</strong> rather than drawing entire cell/row (which takes away load of redrawing label and few other data which can be static)</li></ul><p><strong>BrainStorming:</strong> Way of implementation would be different but need to think over few basic things on how can we implement the screen.</p><ul><li>StockTicker <strong>Model</strong>: Holds stock item with price data.</li><li><strong>ViewModel</strong>: Performs API call, holds stock items, updates stock prices with a Timer and tracks visible items.</li><li><strong>Main Screen</strong>: Renders data in a Listing view. We might create separate views for separate components, like, Listing Row.</li></ul><h3><strong>Let’s take a deep breath and dive now.</strong></h3><h4>StockTicker Model:</h4><pre>import Foundation<br><br>@Observable<br>final class StockTicker: Codable, Identifiable {<br>    let id: UUID<br>    private(set) var value: Double   // Updates data every few seconds<br>    <br>    init(value: Double) {<br>        self.id = UUID()<br>        self.value = value<br>    }<br>    <br>    func updateValue(_ newValue: Double) {<br>        value = newValue<br>    }<br>}</pre><ul><li><strong>Observable</strong>: Need to observe only price property to redraw at minimum level. struct does not have this benefit.</li><li><strong>Class vs Struct</strong>: Observable + dynamic data updates.</li><li><strong>Identifiable</strong>: Uniquely identifies each model in order to redraw a specific model/row.</li></ul><p><em>We marked the model as </em><em>final as we don’t need to inherit it and </em><em>final give a bit of performance boost.</em></p><h4>WatchListingScreenViewModel:</h4><pre>import Combine<br>import Foundation<br><br>@Observable @MainActor<br>final class WatchListingScreenViewModel {<br>    var list = [StockTicker]() // Holds stock items watchlist<br><br>    private var visibleItems = Set&lt;Int&gt;() // Holds on-screen rows<br>    private var timer: AnyCancellable? // Updates stock ticker every few seconds<br>    private let updateDuration: TimeInterval = 15<br>    <br>    init(list: [StockTicker] = [], visibleItems: Set&lt;Int&gt; = []) {<br>        self.list = list<br>        self.visibleItems = visibleItems<br>        self.timer = nil<br>    }<br>    <br>    func startTimer() {<br>        debugPrint(&quot;&gt;&gt;&gt;&gt;&gt; Starting refresh&quot;)<br>        timer = Timer.publish(every: updateDuration, on: .main, in: .common)<br>            .autoconnect()<br>            .sink(receiveValue: { _ in<br>                self.updateValues()<br>            })<br>    }<br>    <br>    func endTimer() {<br>        debugPrint(&quot;&gt;&gt;&gt;&gt;&gt; Ending refresh&quot;)<br>        timer?.cancel()<br>        timer = nil<br>    }<br>    <br>    // Handle row visibility set,<br>    // isVisible only lives in the set, non-visibles are removed,<br>    // so, updates don&#39;t occur for non-visible rows<br>    func updateListItem(_ index: Int, isVisible: Bool) {<br>        guard isVisible else {<br>            debugPrint(&quot;Removing - &quot;, index)<br>            visibleItems.remove(index)<br>            return<br>        }<br>        <br>        debugPrint(&quot;Showing - &quot;, index)<br>        visibleItems.insert(index)<br>    }<br>    <br>    // Check only visible cells and update its values,<br>    // consider API call to fetch updates for each individual stock item is different<br>    func updateValues() {<br>        self.visibleItems.forEach { index in<br>            let item = self.list[index]<br>            // TODO: Update by API call<br>            item.updateValue(item.value + 0.1)<br>        }<br>    }<br>    <br>    // Fetch main listing for WatchList screen, loads data with initial value<br>    func fetchValues() {<br>        // TODO: API call to update newList,<br>        // TODO: self.list should be maintained to update it rather than assignment<br>        var newList = [StockTicker]()<br>        for _ in 0...49 {<br>            newList.append(StockTicker(value: 0.0))<br>        }<br>        <br>        self.list = newList<br>        startTimer()<br>    }<br>}</pre><ul><li><strong>Observable:</strong> View needs to observe the View Model to refresh the view when stock listing is updated. list is observed to update the on-screen Listing.</li><li><strong>MainActor:</strong> View Model is directly controlling SwiftUI Views which are drawn on Main Thread. MainActor confirm all redraw occurs on Main Thread.</li><li><strong>Timer:</strong> Handles refreshing stock prices every 15 seconds.</li><li><strong>VisibleItems:</strong> Handles on-screen stock item listing.</li></ul><p><em>ViewModel handles most of the business logic to fetch the watch listing, controlling timer and updating stock prices based on on-screen stock visibility.</em></p><h4>WatchlistItemView:</h4><p><em>Handles individual stock row item which draws price and other relevant data (not scope of this blog).</em></p><pre>import SwiftUI<br><br>struct WatchlistItemView: View {<br>    @Binding var data: StockTicker<br>    <br>    var body: some View {<br>        VStack(alignment: .leading) {<br>            Text(&quot;Item =&gt; \(String(format: &quot;%.1f&quot;, data.value))&quot;)<br>        }<br>        .frame(maxWidth: .infinity, alignment: .leading)<br>        .background(Color.random)<br>        .padding()<br>    }<br>}</pre><ul><li><strong>Binding vs State:</strong> Binding does not own the property, so, it simply listens to the property owned by the other/parent view. This handles update of the price property and only redraws the price label. State would redraw whole row which is not efficient.</li><li><strong>Color.random</strong>: Debugging mechanism to visibly observe only price label gets changed.</li></ul><h4>Color Extension for debugging purpose:</h4><pre>import SwiftUI<br><br>extension Color {<br>    static var random: Color {<br>        let red = CGFloat.random(in: 0...1)<br>        let green = CGFloat.random(in: 0...1)<br>        let blue = CGFloat.random(in: 0...1)<br>        return Color(red: red, green: green, blue: blue)<br>    }<br>}</pre><p><em>When used as </em><em>Color.random gets a </em><strong><em>random</em></strong><em> color for each call, which visibly reflects which </em><strong><em>View</em></strong><em> is getting redrawn.</em></p><h4>Main Screen — WatchlistingScreenView:</h4><pre>import SwiftUI<br><br>struct WatchlistingScreenView: View {<br>    @State var viewModel: WatchListingScreenViewModel<br>    @Environment(\.scenePhase) var scenePhase<br><br>    var body: some View {<br>        return VStack {<br>            Text(&quot;Available Data =&gt; &quot;)<br>            listingView<br>        }<br>        .background(Color.random)<br>        .task {<br>            viewModel.fetchValues()<br>        }<br>        .onChange(of: scenePhase) {<br>            if scenePhase == .background {<br>                viewModel.endTimer()<br>            } else if scenePhase == .active {<br>                viewModel.startTimer()<br>            }<br>        }<br>    }<br>}<br><br>private extension WatchlistingScreenView {<br>    var listingView: some View {<br>        List {<br>            ForEach(viewModel.list.indices, id: \.self) { index in<br>                WatchlistItemView(data: $viewModel.list[index])<br>                    .background(Color.random)<br>                    .onAppear {<br>                        viewModel.updateListItem(index, isVisible: true)<br>                    }<br>                    .onDisappear {<br>                        viewModel.updateListItem(index, isVisible: false)<br>                    }<br>            }<br>        }<br>    }<br>}</pre><ul><li>@State: The view owns the ViewModel and holds it.</li><li>onAppear and onDisappear handles which cell is being on screen. scenePhase is also handling the visibility of screen, so, in background, the timer totally stops.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb55c6111e09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Power of inout parameters in Swift]]></title>
            <link>https://medium.com/@mobihunterz/power-of-inout-parameters-in-swift-a3ee6054be2d?source=rss-df01e0532538------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3ee6054be2d</guid>
            <dc:creator><![CDATA[Paresh J Thakor]]></dc:creator>
            <pubDate>Tue, 27 May 2025 21:13:04 GMT</pubDate>
            <atom:updated>2025-05-28T00:01:22.976Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrI5z9pVfmtrUL668rsGZg.png" /></figure><p>I came across of inout parameter when I was implementing an example framework. inout is a very powerful and kind of double-edged sword.</p><blockquote>Thanks Pedro and Federico for suggesting usage of inout.</blockquote><p><strong>Definition</strong>: inout parameter <strong>allows modification of the parameter value</strong> inside the function body.</p><p>Swift provides value and reference type variables to manage type-safety. value and reference type is detected when the variable is declared and while working with these types, a developer does not need to declare its type. It’s responsibility of Swift runtime to manage these variables.</p><p>However, inout is a special case and its usage depends on specific cases.</p><h4>Consider an example:</h4><pre>var num1 = 10<br>var num2 = 20<br><br>func swap&lt;T&gt;(_ a: inout T, _ b: inout T) {<br>  (a, b) = (b, a)  // Replaced variables in place<br>}<br><br>swap(&amp;num1, &amp;num2)<br><br>print(num1) // prints 20<br>print(num2) // prints 10</pre><h4>How it works: copy-in copy-out</h4><p>Let me explain how inout defers from pass-by-reference.</p><ul><li><strong>Copy-in</strong>: When a parameter is passed in the function, its value is copied.</li><li><strong>Modify</strong>: The value is modified in the function body.</li><li><strong>Copy-out</strong>: When the function is returned, the parameter value is copied out and assigned to the original variable.</li></ul><h4>Rules:</h4><p>Usage of inout requires to follow certain rules to avoid compiler errors as you have seen above implementation is a bit different from what are general Swift functions.</p><ul><li><strong>Variable Declaration</strong>: Variables need to be defined with var as they will be modified later. let variables can’t be used for inout parameters.</li><li><strong>Function Parameter</strong>: inout keyword is required before parameter type in the function definition.</li><li><strong>Function Call</strong>: &amp; is prefixed for the argument while calling the function. E.g. &amp;num1 and &amp;num2.</li></ul><h4>Applications:</h4><p>I have implemented Swizzling function using inout parameters. Check the example below.</p><ul><li>URLSessionConfiguration extension is added to provide default methods for swizzled default session.</li></ul><pre>/// Adding Session Configuration extension for Swizzling default methods<br>extension URLSessionConfiguration {<br>    <br>    @objc class var swizzledDefault: URLSessionConfiguration {<br>        let config = self.swizzledDefault // calls original `default` now due to swizzling<br>        // Changes to CONFIG<br>        return config<br>    }<br>    <br>    @objc class var swizzledEphemeral: URLSessionConfiguration {<br>        let config = self.swizzledEphemeral // calls original `ephemeral` now due to swizzling<br>        // Changes to CONFIG<br>        return config<br>    }<br>}</pre><ul><li>Implement swizzle method using inout parameter as we need to keep a reference of original method to un-swizzle when required.</li></ul><pre>// Common method to swizzle URLSessionConfiguration methods<br>func swizzleConfiguration(getter: Selector, swizzled: Selector, originalIMP: inout IMP?) {<br>    guard let originalMethod = class_getClassMethod(URLSessionConfiguration.self, getter),<br>          let swizzledMethod = class_getClassMethod(URLSessionConfiguration.self, swizzled) else {<br>        return<br>    }<br><br>    originalIMP = method_getImplementation(originalMethod)<br>    method_exchangeImplementations(originalMethod, swizzledMethod)<br>}</pre><ul><li>To use the above swizzle method check below implementation.</li></ul><pre>// IMP variables are required to keep references of original method implementations<br>private var originalDefaultSessionConfigurationIMP: IMP?<br>private var originalEphemeralSessionConfigurationIMP: IMP?<br><br>swizzleConfiguration(getter: #selector(getter: URLSessionConfiguration.default),<br>                     swizzled: #selector(getter: URLSessionConfiguration.swizzledDefault),<br>                     originalIMP: &amp;originalDefaultSessionConfigurationIMP)<br>    <br>swizzleConfiguration(getter: #selector(getter: URLSessionConfiguration.ephemeral),<br>                     swizzled: #selector(getter: URLSessionConfiguration.swizzledEphemeral),<br>                     originalIMP: &amp;originalEphemeralSessionConfigurationIMP)</pre><ul><li>Let’s un-swizzle the methods with below implementation.</li></ul><pre>// Common method to undo swizzling of URLSessionConfiguration methods<br>func undoSwizzleConfiguration(getter: Selector, originalIMP: inout IMP?) {<br>    guard let originalMethod = class_getClassMethod(URLSessionConfiguration.self, getter),<br>          let originalImp = originalIMP else {<br>        return<br>    }<br><br>    // Restore original method<br>    method_setImplementation(originalMethod, originalImp)<br><br>    // Reset IMP to nil<br>    originalIMP = nil<br>}<br><br>// un-swizzle the method implementations using inout parameter<br>undoSwizzleConfiguration(getter: #selector(getter: URLSessionConfiguration.default),<br>                           originalIMP: &amp;originalDefaultSessionConfigurationIMP)<br>    <br>undoSwizzleConfiguration(getter: #selector(getter: URLSessionConfiguration.ephemeral),<br>                           originalIMP: &amp;originalEphemeralSessionConfigurationIMP)</pre><p>Consider, if you don’t have inout then implementation of such functions will be difficult. We need to create either some generic functions but the implementation will be a bit lengthy.</p><h4>When to use:</h4><ul><li>When modifying value types in the function body.</li><li>Mutation intent is clear.</li></ul><h4>When to avoid:</h4><ul><li>While working with reference types.</li><li>Implementing reusable APIs and avoiding side-effects.</li><li>Overusing to create complex mutation chains. Debugging becomes much more difficult.</li></ul><h4>References:</h4><ul><li><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/functions/#In-Out-Parameters">Apple Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3ee6054be2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>