<?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 Ankit Kumar on Medium]]></title>
        <description><![CDATA[Stories by Ankit Kumar on Medium]]></description>
        <link>https://medium.com/@ankit9deshwal9?source=rss-718e92a470bd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MtKNgicVcPAMk1woNJICWg.jpeg</url>
            <title>Stories by Ankit Kumar on Medium</title>
            <link>https://medium.com/@ankit9deshwal9?source=rss-718e92a470bd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 16:20:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankit9deshwal9/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[iOS 27: 15 New Features Every Developer Should Know (and Swift’s Leap to Android)]]></title>
            <link>https://medium.com/@ankit9deshwal9/ios-27-15-new-features-every-developer-should-know-and-swifts-leap-to-android-eaaa7f4e0b2c?source=rss-718e92a470bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaaa7f4e0b2c</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ankit Kumar]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 05:39:47 GMT</pubDate>
            <atom:updated>2026-11-02T05:39:47.616Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep dive into Apple’s next-generation developer platform, spatial paradigms, and the official revolution in cross-platform Swift development.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6fJmdGNT4tULZkH412RWQ@2x.png" /></figure><p>Every major iOS release shifts the developer paradigm, but <strong>iOS 27</strong> and the latest <strong>Swift toolchain evolution</strong> represent the most significant architectural inflection point since Swift was introduced in 2014.</p><p>Between on-device agentic AI, dynamic spatial rendering across varied form factors, and — the biggest surprise of the decade — <strong>first-class, native Swift toolchains targeting Android</strong>, mobile engineering is officially entering a post-fragmentation era.</p><p>In this guide, we break down the <strong>15 game-changing iOS 27 features</strong> you need to adopt, followed by a dedicated <strong>deep dive into Swift for Android development</strong> with complete architectural code examples.</p><p><strong>1. Local Foundation Models API (AppIntelligenceAgent)</strong></p><p>Developers no longer need to call external cloud LLMs for everyday intelligent workflows. iOS 27 exposes a high-throughput, on-device foundation model through Apple’s unified `AppIntelligenceAgent` framework.</p><p>- <strong>Zero latency &amp; 100% offline privacy</strong>.</p><p>- Structured function-calling directly into your app’s `AppIntent` catalog.</p><p>- Fully typed schema output parsed natively into Swift `Codable` structs.</p><pre>import AppIntelligence<br><br>@AgentActor<br>final class SmartTripPlanner {<br>    private let agent = FoundationModelAgent(model: .balanced)<br><br>    func generateItinerary(prompt: String) async throws -&gt; [TripActivity] {<br>        let response = try await agent.complete(<br>            prompt: prompt,<br>            schema: [TripActivity].self<br>        )<br>        return response.value<br>    }<br>}</pre><p><strong>2. Spatial SwiftUI 3.0 &amp; Volumetric Mesh Modifiers</strong></p><p>SwiftUI now natively bridges 2D screens and spatial volumetric views with dynamic light casting and mesh deformation.</p><pre>import SwiftUI<br><br>struct HeroCardView: View {<br>    @State private var elevation: Float = 0.2<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Spatial Computing&quot;)<br>                .font(.title)<br>                .bold()<br>            Text(&quot;Real-time dynamic refraction &amp; shadow mesh.&quot;)<br>        }<br>        .padding()<br>        .spatialSurface(.liquidGlass(refraction: 0.8))<br>        .volumetricElevation(elevation)<br>        .onSpatialHover { isHovered in<br>            withAnimation(.spring(response: 0.35, dampingFraction: 0.8)) {<br>                elevation = isHovered ? 0.8 : 0.2<br>            }<br>        }<br>    }<br>}</pre><p><strong>3. Declarative Metal Shader Pipeline (`@MetalShader`)</strong></p><p>Gone are the days of manual pipeline descriptors and MSL bridge headers for basic visual effects. iOS 27 introduces the `@MetalShader` macro.</p><pre>import SwiftUI<br>import MetalShaders<br><br>@MetalShader(source: &quot;&quot;&quot;<br>    [[stitchable]] half4 chromaShift(float2 position, half4 color, float2 size, float time) {<br>        float2 uv = position / size;<br>        half r = half(sin(uv.x * 10.0 + time));<br>        return half4(r, color.g, color.b, color.a);<br>    }<br>&quot;&quot;&quot;)<br>struct ChromaticEffect: ViewModifier {<br>    var time: Float<br>    <br>    func body(content: Content) -&gt; some View {<br>        content.colorEffect(ShaderLibrary.chromaShift(.float(time)))<br>    }<br>}</pre><p><strong>4. Zero-Copy Memory Buffers in Swift Concurrency</strong></p><p>For camera pipelines, audio synthesis, and neural streams, Swift’s ownership model now provides zero-copy contiguous memory borrowing across actors without runtime allocation locks.</p><pre>actor VideoFrameProcessor {<br>    func processFrame(buffer: consuming InlineMemoryBuffer&lt;UInt8&gt;) async -&gt; ProcessedMetrics {<br>        // Operates directly on the shared GPU/NPU memory space<br>        let metrics = buffer.withUnsafeSpan { span in<br>            analyzeLuminance(span)<br>        }<br>        return metrics<br>    }<br>}</pre><p><strong>5. Universal Intent Bus 2.0 (Multi-App Inter-Agent Actions)</strong></p><p>iOS 27 allows your app to register modular micro-actions that other apps (or Siri’s multi-step agent) can chain safely in an isolated sandbox.</p><pre>import AppIntents<br><br>struct BookHotelIntent: AppIntent {<br>    static var title: LocalizedStringResource = &quot;Book Hotel&quot;<br>    <br>    @Parameter(title: &quot;City&quot;)<br>    var city: String<br>    <br>    @Parameter(title: &quot;Nights&quot;)<br>    var nights: Int<br><br>    func perform() async throws -&gt; some IntentResult &amp; ReturnsValue&lt;BookingConfirmation&gt; {<br>        let confirmation = try await HotelBookingService.shared.reserve(city: city, nights: nights)<br>        return .result(value: confirmation)<br>    }<br>}</pre><p><strong>6. Post-Quantum CryptoKit (`PQCryptoKit`)</strong></p><p>Apple has upgraded cryptographic baselines to post-quantum key encapsulation (ML-KEM) and digital signatures (ML-DSA).</p><pre>import CryptoKit<br>import PQCryptoKit<br><br>func createQuantumSafeHandshake() throws -&gt; (publicKeyData: Data, sharedSecret: SymmetricKey) {<br>    let alicePrivateKey = PQCryptoKit.ML_KEM.PrivateKey()<br>    let alicePublicKey = alicePrivateKey.publicKey<br>    <br>    let (ciphertext, sharedSecret) = try alicePublicKey.encapsulate()<br>    return (ciphertext, sharedSecret)<br>}</pre><p><strong>7. Dynamic Screen Continuum &amp; Foldable Adaptability</strong></p><p>With upcoming flexible form factors, SwiftUI’s new geometry environment variables let you respond to hinges, fold angles, and secondary back-displays without guesswork.</p><pre>struct FoldableMasterDetailView: View {<br>    @Environment(\.displayHingeAngle) private var hingeAngle<br>    @Environment(\.displayFoldState) private var foldState<br><br>    var body: some View {<br>        if foldState == .halfFolded {<br>            VStack {<br>                TopScreenControls()<br>                BottomScreenKeyboard()<br>            }<br>        } else {<br>            HStack {<br>                SidebarView()<br>                ContentView()<br>            }<br>        }<br>    }<br>}</pre><p><strong>8. Ambient Passkeys 2.0 (Continuous Zero-Touch Verification)</strong></p><p>Passkeys now support ambient cryptographic session validation backed by UWB and on-device biometric telemetry, eliminating repetitive face-scan prompts during high-security transactions.</p><p><strong>9. Neural Haptic Synthesis (`FluidHapticsEngine`)</strong></p><p>Synthesize dynamic, continuous haptic waveforms calculated in real time by your app’s physics engines instead of static `.light`, `.medium`, or `.heavy` presets.</p><pre>import CoreHaptics<br><br>func triggerElasticBounce(velocity: Double) {<br>    let wave = ContinuousHapticWaveform(<br>        frequencyEnvelope: [0.0: 120, 0.2: 240, 0.4: 80],<br>        amplitudeEnvelope: [0.0: Float(velocity), 0.4: 0.0]<br>    )<br>    FluidHapticsEngine.shared.play(wave)<br>}</pre><p><strong>10. Instant Micro-App Bundles (Sub-5MB Edge Execution)</strong></p><p>Apple App Store now allows dynamic micro-binary slicing where cold start code streams in chunks, dropping initial cold launch latency under <strong>120ms.</strong></p><p><strong>11. Autonomous Background Engine 2.0</strong></p><p>Background execution now leverages device battery telemetry, local solar prediction, and grid energy pricing to intelligently schedule compute-heavy ML and synchronization jobs.</p><p><strong>12. Privacy Proof Kit (`PrivacyProofKit`)</strong></p><p>Generate cryptographic zero-knowledge proofs (ZKPs) verifying user age, location boundaries, or subscription status without sharing raw PII with third-party backend servers.</p><p><strong>13. Multipeer Live State Engine (`StateSyncKit`)</strong></p><p>P2P and CloudKit CRDTs (Conflict-free Replicated Data Types) built directly into SwiftUI `@StateSync` macros for real-time collaborative document editing.</p><pre>import StateSyncKit<br><br>@ModelSync<br>final class CollaborativeCanvas {<br>    var shapes: [CanvasShape] = []<br>    var activeParticipants: Set&lt;String&gt; = []<br>}</pre><p><strong>14. Spatial Audio Synthesis (`SpatialAcousticsKit`)</strong></p><p>Simulate real-world room geometry and acoustic occlusion for audio streams in real time with hardware-accelerated ray tracing.</p><p><strong>15. Smart Instruments &amp; AI Regression Detection</strong></p><p>Xcode Instruments now includes automated timeline reasoning: it flags memory fragmentation, actor contention, and frame drops before they ever hit production.</p><h3><strong>Part 2: Deep Dive — Swift Goes Native on Android</strong></h3><p>The most groundbreaking shift for the Swift community is <strong>Apple and the Swift Core Project’s official cross-platform Android toolchain integration</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UuQzK-cV_-x-UTd3NqhOGQ.png" /></figure><p><strong>Why Swift on Android Outperforms Existing Solutions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l12AfS18n9Sq8UNYT5HTJA.png" /></figure><h4><strong>Building a Shared Swift Core for iOS &amp; Android</strong></h4><p>Here is how you can write a shared Swift module and consume it seamlessly across <strong>iOS (SwiftUI)</strong> and <strong>Android (Kotlin + Jetpack Compose)</strong>.</p><p><strong>Step 1: The Shared Swift Business Logic Module</strong></p><pre>import Foundation<br><br>public struct UserProfile: Codable, Sendable {<br>    public let id: String<br>    public let username: String<br>    public let email: String<br>    public let isPro: Bool<br><br>    public init(id: String, username: String, email: String, isPro: Bool) {<br>        self.id = id<br>        self.username = username<br>        self.email = email<br>        self.isPro = isPro<br>    }<br>}<br><br>public actor UserManager {<br>    public static let shared = UserManager()<br>    <br>    private var cachedProfile: UserProfile?<br><br>    public init() {}<br><br>    public func fetchUserProfile(userId: String) async throws -&gt; UserProfile {<br>        // Simulated network request<br>        try await Task.sleep(nanoseconds: 500_000_000)<br>        <br>        let profile = UserProfile(<br>            id: userId,<br>            username: &quot;swift_dev_2027&quot;,<br>            email: &quot;developer@swift.org&quot;,<br>            isPro: true<br>        )<br>        self.cachedProfile = profile<br>        return profile<br>    }<br><br>    public func isUserSubscribed() -&gt; Bool {<br>        return cachedProfile?.isPro ?? false<br>    }<br>}</pre><p><strong>Step 2: Swift Java/Kotlin Interop Bridge (Swift Macros)</strong></p><p>Using the new `@JavaExport` Swift macro, Swift automatically generates JNI headers and companion Kotlin wrappers at compile time:</p><pre><br>import JavaKit<br>import JavaKitMacro<br><br>@JavaExport<br>public final class AndroidUserBridge {<br>    private let manager = UserManager.shared<br><br>    @JavaMethod<br>    public func fetchUser(userId: String, completion: @escaping (String?, String?) -&gt; Void) {<br>        Task {<br>            do {<br>                let user = try await manager.fetchUserProfile(userId: userId)<br>                let jsonData = try JSONEncoder().encode(user)<br>                let jsonString = String(data: jsonData, encoding: .utf8)<br>                completion(jsonString, nil)<br>            } catch {<br>                completion(nil, error.localizedDescription)<br>            }<br>        }<br>    }<br>}</pre><p><strong>Step 3: Consuming in Android with Jetpack Compose</strong></p><pre>package com.example.androidapp<br><br>import android.os.Bundle<br>import androidx.activity.ComponentActivity<br>import androidx.activity.compose.setContent<br>import androidx.compose.foundation.layout.*<br>import androidx.compose.material3.*<br>import androidx.compose.runtime.*<br>import androidx.compose.ui.Alignment<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.unit.dp<br>import kotlinx.coroutines.launch<br>import com.swift.generated.AndroidUserBridge<br><br>class MainActivity : ComponentActivity() {<br>    private val swiftBridge = AndroidUserBridge()<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            MaterialTheme {<br>                UserProfileScreen(swiftBridge)<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>fun UserProfileScreen(bridge: AndroidUserBridge) {<br>    val coroutineScope = rememberCoroutineScope()<br>    var userJson by remember { mutableStateOf&lt;String?&gt;(&quot;Loading from Swift core...&quot;) }<br><br>    LaunchedEffect(Unit) {<br>        bridge.fetchUser(&quot;usr_9921&quot;) { jsonResult, error -&gt;<br>            userJson = jsonResult ?: &quot;Error: $error&quot;<br>        }<br>    }<br><br>    Surface(modifier = Modifier.fillMaxSize()) {<br>        Column(<br>            modifier = Modifier.padding(24.dp),<br>            verticalArrangement = Arrangement.Center,<br>            horizontalAlignment = Alignment.CenterHorizontally<br>        ) {<br>            Text(&quot;Android UI (Jetpack Compose)&quot;, style = MaterialTheme.typography.headlineMedium)<br>            Spacer(modifier = Modifier.height(16.dp))<br>            Card(modifier = Modifier.fillMaxWidth()) {<br>                Text(<br>                    text = userJson ?: &quot;No Data&quot;,<br>                    modifier = Modifier.padding(16.dp),<br>                    style = MaterialTheme.typography.bodyLarge<br>                )<br>            }<br>        }<br>    }<br>}</pre><p><strong>Step 4: Consuming in iOS with SwiftUI</strong></p><pre><br>import SwiftUI<br>import SharedCore<br><br>struct UserProfileView: View {<br>    @State private var profile: UserProfile?<br>    @State private var isLoading = true<br>    @State private var errorMessage: String?<br><br>    var body: some View {<br>        NavigationStack {<br>            VStack(spacing: 20) {<br>                if isLoading {<br>                    ProgressView(&quot;Calling Swift Core Actor...&quot;)<br>                } else if let profile = profile {<br>                    VStack(alignment: .leading, spacing: 12) {<br>                        Text(&quot;Username: \(profile.username)&quot;)<br>                            .font(.headline)<br>                        Text(&quot;Email: \(profile.email)&quot;)<br>                            .font(.subheadline)<br>                            .foregroundColor(.secondary)<br>                        <br>                        Label(<br>                            profile.isPro ? &quot;Pro Subscriber&quot; : &quot;Free Plan&quot;,<br>                            systemImage: profile.isPro ? &quot;checkmark.seal.fill&quot; : &quot;person&quot;<br>                        )<br>                        .foregroundColor(profile.isPro ? .green : .gray)<br>                    }<br>                    .padding()<br>                    .frame(maxWidth: .infinity)<br>                    .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 16))<br>                } else if let error = errorMessage {<br>                    Text(&quot;Error: \(error)&quot;)<br>                        .foregroundColor(.red)<br>                }<br>            }<br>            .padding()<br>            .navigationTitle(&quot;iOS (SwiftUI)&quot;)<br>            .task {<br>                do {<br>                    profile = try await UserManager.shared.fetchUserProfile(userId: &quot;usr_9921&quot;)<br>                    isLoading = false<br>                } catch {<br>                    errorMessage = error.localizedDescription<br>                    isLoading = false<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>Developer Action Plan: How to Prepare Your Projects</strong></p><p>1. <strong>Enforce Complete Swift 6 Strict Concurrency</strong>: Audit your codebase with strict data isolation checks (`-strict-concurrency = complete`) to guarantee thread safety when compiling shared binaries for Android.</p><p>2. <strong>Decouple UI from Core Architecture</strong>: Extract networking, persistence (SQLite/GRDB/SwiftData), and business validation into pure Swift packages with zero UIKit or AppKit dependencies.</p><p>3. <strong>Adopt AppIntents Early</strong>: Structure your user actions as intent contracts today so they can be immediately orchestrated by iOS 27’s Foundation Agent bus.</p><p>4. <strong>Benchmark Swift SPM Android Toolchain</strong>: Run automated CI test matrices targeting both `aarch64-unknown-linux-android` and `arm64-apple-ios`.</p><p><strong>Conclusion</strong></p><p>iOS 27 and cross-platform Swift mark the end of forced compromises. You no longer have to choose between writing repetitive business logic twice or sacrificing 120 FPS native responsiveness with generic web wrappers.</p><p>With <strong>Swift as your unified, high-performance native core</strong> and <strong>SwiftUI / Jetpack Compose as your tailored platforms</strong>, mobile development is faster, safer, and more expressive than ever.</p><p><em>What iOS 27 feature are you most excited to try in your apps? Have you started experimenting with Swift on Android? Let’s discuss in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaaa7f4e0b2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How an iOS Developer Can Build a Swift Project That Runs on Android: A Complete Step-by-Step Guide]]></title>
            <link>https://medium.com/@ankit9deshwal9/how-an-ios-developer-can-build-a-swift-project-that-runs-on-android-a-complete-step-by-step-guide-6d53dc3b5f6f?source=rss-718e92a470bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d53dc3b5f6f</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[hybrid-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Ankit Kumar]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 11:12:11 GMT</pubDate>
            <atom:updated>2026-10-18T13:20:24.313Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Stop rewriting your business logic in Kotlin. Here is how to architect, cross-compile, and run pure Swift on Android — directly from Xcode with Cmd + R.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FHWwpIUJMS_vFMI63VgmA.png" /></figure><p>For over a decade, mobile software engineering teams have struggled with the same painful trade-off: <strong>Do we write every single feature twice</strong> — once in Swift for iOS and again in Kotlin for Android — or do we surrender to a meta-framework like Flutter or React Native, sacrificing native Apple Human Interface Guidelines and raw platform ergonomics?</p><p>Kotlin Multiplatform (KMP) made huge waves in recent years. But let’s be honest: KMP was built <em>by Android developers, for Android developers</em>. As an iOS developer, KMP forces you into unfamiliar Gradle scripts, JVM memory models, and awkward CocoaPods or Swift Package Manager bridge wrappers.</p><blockquote>💡 The Swift 6 Paradigm Shift:<br>Swift is now an officially supported first-class citizen on Android via the Swift on Android Workgroup. With Swift 6’s strict concurrency, Actors, and Sendable models, your business logic can be written once in pure Swift and run natively on both iOS and Android — all orchestrated directly from your familiar Xcode workspace!</blockquote><h3>The Architecture: One Swift Brain, Two Native Faces</h3><p>Rather than attempting to hack UIKit onto Android, the modern, scalable approach splits your mobile app into clean, idiomatic layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_y9QdlEhkmNNHjzA0vlzYg.png" /></figure><h3>Step 1: Setting Up the Android Toolchain on Your Mac</h3><p>To allow Xcode to build for Android, your macOS machine needs the Android NDK and SDK CLI tools installed. Add these exports to your ~/.zshrc:</p><pre># Android SDK &amp; Toolchain<br>export ANDROID_HOME=$HOME/Library/Android/sdk<br>export ANDROID_NDK_HOME=$ANDROID_HOME/ndk/$(ls $ANDROID_HOME/ndk 2&gt;/dev/null | tail -n 1)<br><br># Java / JDK (use Android Studio&#39;s bundled JBR or system Java)<br>export JAVA_HOME=&quot;/Applications/Android Studio.app/Contents/jbr/Contents/Home&quot;<br><br>export PATH=$PATH:$ANDROID_HOME/platform-tools:$ANDROID_HOME/cmdline-tools/latest/bin:$JAVA_HOME/bin<br><br># Verify ADB connection<br>adb devices</pre><h3>Step 2: Defining the Pure Swift 6 Core (SharedCore)</h3><p>Create a Swift Package with strict concurrency enabled. Here is what your Package.swift looks like:</p><pre>// swift-tools-version: 6.0<br>import PackageDescription<br><br>let package = Package(<br>    name: &quot;SharedCore&quot;,<br>    platforms: [.iOS(.v17), .macOS(.v14)],<br>    products: [<br>        .library(name: &quot;SharedCore&quot;, targets: [&quot;SharedCore&quot;]),<br>        .library(name: &quot;AndroidBridge&quot;, targets: [&quot;AndroidBridge&quot;])<br>    ],<br>    targets: [<br>        .target(<br>            name: &quot;SharedCore&quot;,<br>            swiftSettings: [.enableUpcomingFeature(&quot;StrictConcurrency&quot;)]<br>        ),<br>        .target(<br>            name: &quot;AndroidBridge&quot;,<br>            dependencies: [&quot;SharedCore&quot;],<br>            swiftSettings: [.enableUpcomingFeature(&quot;StrictConcurrency&quot;)]<br>        )<br>    ]<br>)</pre><p>Next, define your thread-safe Swift Actor inside UserManager.swift. Because it is an actor, it prevents data races across both iOS and Android background threads automatically:</p><pre>import Foundation<br><br>public actor UserManager {<br>    public static let shared = UserManager()<br>    private var cachedProfile: UserProfile?<br><br>    public func fetchUserProfile(userId: String) async throws -&gt; UserProfile {<br>        // High-performance asynchronous actor execution<br>        try await Task.sleep(nanoseconds: 300_000_000)<br>        let profile = UserProfile(<br>            id: userId,<br>            username: &quot;swift_dev_2027&quot;,<br>            email: &quot;developer@swift.org&quot;,<br>            isPro: true<br>        )<br>        self.cachedProfile = profile<br>        return profile<br>    }<br>}</pre><h3>Step 3: The JNI Bridge (Connecting Swift to Kotlin)</h3><p>The Android Runtime (ART) communicates with native C/C++ and Swift libraries through the <strong>Java Native Interface (JNI)</strong>. We write a lightweight Swift bridge that serializes output to JSON strings or binary buffers and invokes the Android completion callback:</p><pre>import Foundation<br>import SharedCore<br><br>public final class AndroidUserBridge: @unchecked Sendable {<br>    private let manager = UserManager.shared<br><br>    public func fetchUser(userId: String, completion: @escaping @Sendable (String?, String?) -&gt; Void) {<br>        Task {<br>            do {<br>                let user = try await manager.fetchUserProfile(userId: userId)<br>                let jsonData = try JSONEncoder().encode(user)<br>                completion(String(data: jsonData, encoding: .utf8), nil)<br>            } catch {<br>                completion(nil, error.localizedDescription)<br>            }<br>        }<br>    }<br>}</pre><h3>Step 4: The Holy Grail — Running Android from Xcode!</h3><p>Here is the secret weapon that makes this workflow unforgettable: <strong>You do not have to leave Xcode to run the Android app!</strong></p><p>1. In Xcode, go to <strong>File &gt; New &gt; Target</strong></p><p>2. Scroll to the <strong>Other</strong> section and select <strong>Aggregate</strong> (or External Build System with a Makefile).</p><p>3. Name the target: <strong>AndroidApp or (name you prefer)</strong>.</p><p>4. Go to the target’s <strong>Build Phases</strong> tab and click <strong>+ &gt; New Run Script Phase</strong>:</p><pre>#!/bin/bash<br># Export Android and Java environments (needed because Xcode runs in a clean shell)<br>export ANDROID_HOME=&quot;$HOME/Library/Android/sdk&quot;<br>if [ -z &quot;$JAVA_HOME&quot; ]; then<br>    export JAVA_HOME=&quot;/Applications/Android Studio.app/Contents/jbr/Contents/Home&quot;<br>fi<br>export PATH=&quot;$JAVA_HOME/bin:$ANDROID_HOME/platform-tools:$PATH&quot;<br>cd &quot;${SRCROOT}/AndroidAppSample&quot;<br># 1. Compile the APK<br>./gradlew assembleDebug<br># 2. Check for connected Android device or running emulator<br>ACTIVE_DEVICE=$(adb devices | awk &#39;NR&gt;1 &amp;&amp; $2==&quot;device&quot; {print $1; exit}&#39;)<br>if [ -n &quot;$ACTIVE_DEVICE&quot; ]; then<br>    echo &quot;📲 Deploying to: $ACTIVE_DEVICE&quot;<br>    ./gradlew installDebug<br>    adb -s &quot;$ACTIVE_DEVICE&quot; shell am start -n &quot;com.example.androidapp/.MainActivity&quot;<br>else<br>    echo &quot;⚠️ APK built successfully. Connect an Android device with USB debugging or start an emulator to auto-launch!&quot;<br>fi</pre><p>5. Click the Scheme dropdown at the top of Xcode, select <strong>Manage Schemes… &gt; New Scheme</strong>, select target <strong>AndroidApp</strong>, and name it <strong>Android (Pixel Emulator)</strong>.</p><p>Now, whenever you press <strong>Cmd + R</strong>, Xcode builds your shared Swift code, packages the Android APK, deploys it to your connected device or emulator, and launches the app!</p><h3>The Alternative: Skip (100% SwiftUI on Android)</h3><p>If your team wants to write <em>both UI and logic</em> in SwiftUI without writing separate Jetpack Compose code, you should evaluate <strong>Skip.tools</strong>:</p><pre>brew install skiptools/skip/skip<br>skip init --appid=com.company.DualApp dual-app DualApp<br>cd dual-app &amp;&amp; xed .</pre><p>Skip transpiles your SwiftUI views into Compose components on-the-fly inside Xcode, giving you true dual-platform execution with a single UI codebase.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGJFHyAnVCtk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGJFHyAnVCtk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGJFHyAnVCtk%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/33d63ccddbcd69cd0e5b455a349552b0/href">https://medium.com/media/33d63ccddbcd69cd0e5b455a349552b0/href</a></iframe><h3>Conclusion: Swift’s Multiplatform Era Has Arrived</h3><p>We are no longer restricted to Apple’s walled garden. Swift’s ergonomics, compile-time safety, and modern concurrency make it the premier choice for shared core logic. By letting Xcode drive both builds, iOS developers can expand their engineering reach to billions of Android users without sacrificing the joy of writing Swift every single day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d53dc3b5f6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Concurrency Interview Questions Every iOS Developer Should Know]]></title>
            <link>https://medium.com/@ankit9deshwal9/swift-concurrency-interview-questions-every-ios-developer-should-know-657a2a57e47e?source=rss-718e92a470bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/657a2a57e47e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Ankit Kumar]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 10:00:32 GMT</pubDate>
            <atom:updated>2026-07-08T10:00:32.718Z</atom:updated>
            <content:encoded><![CDATA[<p>Structured concurrency is one of those topics that separates developers who <em>know Swift’s syntax</em> from developers who <em>understand what’s actually happening under the hood</em>. Nowhere is this more obvious than in SwiftUI ViewModels, where a single misplaced Task {} can silently break your app&#39;s data flow.</p><p>Below are Seven interview questions I like to ask mid-level to senior iOS candidates. They all revolve around the same tiny snippet of code, but each question digs one layer deeper — from “spot the bug” to “explain actor isolation and cancellation.” If you can answer all six confidently, you have a solid grip on Swift concurrency.</p><p>Let’s dig in.</p><h4><strong>1. What is wrong with this code?</strong></h4><pre>@MainActor<br>final class UserViewModel: ObservableObject {<br><br>    @Published var users: [User] = []<br><br>    func fetchUsers() async {<br>        Task {<br>            let users = await api.fetchUsers()<br>            self.users = users<br>        }<br>    }<br>}</pre><p>At first glance this looks harmless — it’s async, it awaits an API call, it updates a @Published property. What could go wrong?</p><p>The problem is the Task {} wrapper inside an already async function. Here&#39;s why it matters:</p><ul><li><strong>Task {} is unnecessary inside an </strong><strong>async function.</strong> You&#39;re already in an asynchronous context. Wrapping more async work in a new Task doesn&#39;t add capability — it adds a layer of indirection you didn&#39;t need.</li><li><strong>fetchUsers() returns immediately instead of waiting for the fetch.</strong> Creating a Task schedules work to run <em>later</em>, on its own execution timeline. The outer fetchUsers() function doesn&#39;t await that inner task, so it returns as soon as the Task is <em>created</em>, not when it <em>finishes</em>.</li><li><strong>It breaks structured concurrency.</strong> Structured concurrency’s entire promise is that a parent task’s lifetime encloses its children’s lifetimes. An unstructured Task {} detaches from that hierarchy — it becomes its own independent unit of work with no parent to answer to.</li><li><strong>Cancellation and error propagation no longer follow the caller.</strong> If the caller cancels the outer operation, the inner Task doesn&#39;t know or care. It keeps running.</li></ul><blockquote>“The Task captures self strongly. It doesn&#39;t create a retain cycle because the ViewModel doesn&#39;t own the task, but it can unnecessarily extend the ViewModel&#39;s lifetime if the task runs for a long time. If I want the ViewModel to be released when the user leaves the screen, I&#39;d capture self weakly or restructure the code so the caller manages the task.&quot;</blockquote><p>The fix is almost insultingly simple:</p><pre>func fetchUsers() async {<br>    let users = await api.fetchUsers()<br>    self.users = users<br>}<br>//No Task, no problem.</pre><h4><strong>2. Will </strong><strong>users.count always contain the fetched users?</strong></h4><pre>@MainActor<br>final class UserViewModel: ObservableObject {<br><br>    @Published var users: [User] = []<br><br>    func fetchUsers() async {<br>        Task {<br>            let users = await api.fetchUsers()<br>            self.users = users<br>        }<br>    }<br>}<br>// Callling fetchUsers<br>let viewModel = UserViewModel()<br>await viewModel.fetchUsers()<br>print(viewModel.users.count)</pre><p>This is where the bug becomes observable, not just theoretical.</p><p><strong>With the buggy </strong><strong>Task {} version:</strong> No. await viewModel.fetchUsers() resumes as soon as the outer function returns, which happens right after the inner Task is scheduled — not after it completes. So print(viewModel.users.count) may very well execute <em>before</em> the fetch finishes, printing 0 (or stale data) instead of the freshly fetched count. Worse, this is a race condition: it might work correctly in a debug build and fail in production, or vice versa, depending on timing.</p><p><strong>With the corrected version:</strong> Yes. Since there’s no detached Task, the await inside fetchUsers() genuinely suspends the caller until api.fetchUsers() returns and self.users is assigned. By the time await viewModel.fetchUsers() resumes, self.users is guaranteed to hold the fetched data.</p><p>This is a great follow-up question because it takes the abstract concept of “structured vs. unstructured” and turns it into something a candidate can actually picture: a race condition that only reveals itself under specific timing.</p><pre>@MainActor<br>final class UserViewModel: ObservableObject {<br><br>    @Published var users: [User] = []<br><br>    func fetchUsers() async {<br>// Fixed remove Task<br>     //  Task {<br>            let users = await api.fetchUsers()<br>            self.users = users<br>      //   }<br>    }<br>}<br>// Callling fetchUsers<br>let viewModel = UserViewModel()<br>await viewModel.fetchUsers()<br>print(viewModel.users.count)</pre><h4><strong>3. Why is </strong><strong>@MainActor commonly applied to an entire SwiftUI ViewModel?</strong></h4><pre>@MainActor<br>final class UserViewModel: ObservableObject {<br>    @Published var users: [User] = []<br>}</pre><p>Slapping @MainActor on the whole class (rather than individual methods or properties) is a common — and generally good — pattern in SwiftUI apps. Reasons include:</p><ul><li><strong>It guarantees UI state is modified on the main actor.</strong> @Published properties feed directly into SwiftUI views. Mutating them off the main thread is undefined behavior at best and a crash at worst.</li><li><strong>It prevents accidental background updates.</strong> Without class-level isolation, it’s easy for one method to forget an explicit MainActor.run or await MainActor.run { ... } and quietly introduce a threading bug.</li><li><strong>It removes the need for repeated </strong><strong>MainActor.run calls.</strong> Instead of scattering actor-hopping boilerplate through every method, you isolate the whole type once and let the compiler enforce it everywhere.</li></ul><p>The tradeoff — and a good candidate should mention this — is that <em>everything</em> in the class now runs on the main actor by default, including work that doesn’t need to. If you have genuinely expensive computation, you’ll want to explicitly move it off the main actor (e.g., with a separate nonisolated function or a background actor) rather than doing it inline in a @MainActor-isolated method.</p><h4><strong>4. Does </strong><strong>Task { } inside a </strong><strong>@MainActor method run on a background thread?</strong></h4><pre>@MainActor<br>func load() async {<br>    Task {<br>        let users = await api.fetchUsers()<br>        self.users = users<br>    }<br>}</pre><p>This question trips up a lot of developers, because “Task” and “background” have become mentally fused for many people coming from GCD-style thinking. The truth is more nuanced:</p><ul><li><strong>No, </strong><strong>Task {} inherits the current actor context.</strong> By default, a new Task created inside a @MainActor-isolated function inherits that actor isolation.</li><li><strong>It starts on the </strong><strong>MainActor.</strong> The task doesn&#39;t get dispatched to some anonymous background queue just because it&#39;s wrapped in Task {}.</li><li><strong>During </strong><strong>await, the actor is suspended, not blocked.</strong> When api.fetchUsers() is an async call that hops off-actor (e.g., a network request), the MainActor is free to do other work while waiting — but the <em>task itself</em> isn&#39;t &quot;on a background thread&quot; in the GCD sense.</li><li><strong>After the </strong><strong>await, execution resumes on the </strong><strong>MainActor.</strong> Once api.fetchUsers() returns, control comes back to MainActor-isolated code.</li><li><strong>Actor isolation is preserved throughout.</strong> This is why self.users = users compiles without complaint — the compiler knows this line still executes on the MainActor.</li></ul><p>So the <em>unstructured</em> nature of the inner Task is a real problem (as established in Q1–Q3), but &quot;it silently escapes to a background thread&quot; is <strong>not</strong> the problem. It&#39;s still isolated correctly — it&#39;s just detached from the calling function&#39;s lifecycle.</p><h4>5. How does cancellation behave in these two implementations?</h4><pre>// version 1 ------------&gt;<br>func fetchUsers_1() async {<br>    Task {<br>        let users = await api.fetchUsers()<br>        self.users = users<br>    }<br>}<br>let task1 = Task {<br>    await viewModel.fetchUsers_1()<br>}<br><br>task1.cancel()<br><br>// version 2 ------------&gt;<br><br>func fetchUsers_2() async {<br>    let users = await api.fetchUsers()<br>    self.users = users<br>}<br>let task2 = Task {<br>    await viewModel.fetchUsers_2()<br>}<br>task2.cancel()</pre><p>This is the payoff question — it ties everything together around cancellation, arguably the most practically important consequence of structured vs. unstructured concurrency.</p><ul><li><strong>In the first version, the inner </strong><strong>Task is unstructured and continues unless explicitly cancelled.</strong> Calling task.cancel() on the <em>outer</em> task sets a cancellation flag on that outer task. But the inner Task {} inside fetchUsers() is a completely separate task tree. It has no idea the outer task was cancelled, so api.fetchUsers() keeps running and self.users still gets assigned — even though the caller has &quot;moved on.&quot;</li><li><strong>In the second version, cancellation naturally propagates through the async call chain.</strong> Because there’s no detached task, fetchUsers() is just a continuation of the same structured task. When task.cancel() is called, that cancellation flag is visible all the way down the await chain, and cooperative cancellation checks (like Task.checkCancellation(), or cancellation-aware APIs like URLSession) can respond appropriately.</li><li><strong>This is one of the key benefits of structured concurrency.</strong> Parent-child task relationships mean cancellation, priority, and even task-local values flow predictably through your call stack. Break that structure with an unstructured Task {}, and you lose all of it — quietly, with no compiler warning.</li></ul><h4>6. Find the issue with this code</h4><pre>@MainActor<br>final class UserViewModel: ObservableObject {<br>    @Published var users: [User] = []<br>    @Injected private let api: APIClient<br><br><br>    func startPolling() {<br>        Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { _ in<br>            Task {<br>                let fetched = await self.api.fetchUsers()<br>                self.users = fetched<br>            }<br>        }<br>    }<br>}</pre><p>What’s wrong with this code, and why might UserViewModel never get deallocated even after the view that owns it disappears?</p><h4>Explanation</h4><p>This is a classic <strong>retain cycle</strong>, just wearing a slightly different disguise than the usual “two objects holding strong references to each other.”</p><ul><li><strong>Timer.scheduledTimer retains its closure strongly</strong>, and it keeps firing — and therefore keeps retaining that closure — for as long as the timer is running (which, with repeats: true and no invalidation, is forever).</li><li><strong>The closure captures </strong><strong>self strongly</strong> (the default capture behavior in Swift). So the chain becomes: Timer → strongly retains → closure → strongly retains → UserViewModel (self).</li><li><strong>UserViewModel never explicitly retains the </strong><strong>Timer</strong> in this snippet, but it doesn&#39;t need to — the Timer is scheduled on the run loop, which holds it alive on its own. So you get a cycle in effect: the run loop keeps the timer alive, the timer keeps self alive, and self never gets a chance to deinit and invalidate the timer — because deinit is exactly the thing this cycle prevents from ever running.</li><li><strong>Practical consequence:</strong> even after the SwiftUI view holding this @StateObject disappears, UserViewModel — and everything it holds, including api — stays in memory, silently firing network requests every 5 seconds forever. This is a memory leak that&#39;s also an <em>active</em> leak, not just wasted memory sitting idle.</li></ul><p>The fix is the usual tool for this job: capture self weakly inside the closure, and also make sure the timer itself gets invalidated at some point so the cycle doesn&#39;t need to rely on weak self alone to be safe.</p><pre> @MainActor<br>final class UserViewModel: ObservableObject {<br>    @Published var users: [User] = []<br>    @Injected private let api: APIClient<br>    private var pollingTimer: Timer?<br><br>    func startPolling() {<br>        pollingTimer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { [weak self] _ in<br>            guard let self else { return }<br>            Task {<br>                let fetched = await self.api.fetchUsers()<br>                self.users = fetched<br>            }<br>        }<br>    }<br><br>    func stopPolling() {<br>        pollingTimer?.invalidate()<br>        pollingTimer = nil<br>    }<br><br>    deinit {<br>        pollingTimer?.invalidate()<br>    }<br>}</pre><p><strong>What changed, and why each part matters:</strong></p><ul><li><strong>[weak self] in the timer&#39;s closure</strong> breaks the strong reference from the closure back to self. Now the chain is: Timer → strongly retains → closure → <em>weakly</em> references → UserViewModel. self can be deallocated even while the timer is still technically alive, because nothing forces it to stay.</li><li><strong>guard let self else { return }</strong> safely unwraps the weak reference each time the timer fires. If self has already been deallocated, the closure just returns early instead of crashing or operating on a dangling reference.</li><li><strong>Storing the timer in </strong><strong>pollingTimer and invalidating it (in </strong><strong>stopPolling() and in </strong><strong>deinit)</strong> is the other half of the fix — weak self prevents the <em>leak</em>, but it doesn&#39;t stop the timer from continuing to fire uselessly on a nil self forever. Explicitly invalidating the timer when it&#39;s no longer needed is what actually stops the polling, rather than just making it harmless.</li></ul><h4>7. Find the issue with this code</h4><pre>import SwiftUI<br><br>struct User: Decodable, Identifiable {<br>    let id: Int<br>    let name: String<br>}<br><br>final class UserViewModel: ObservableObject {<br><br>    @Published var users: [User] = []<br>    @Published var isLoading = false<br><br>    func fetchUsers() {<br><br>        isLoading = true<br><br>        Task {<br><br>            let url = URL(string: &quot;https://api.example.com/users&quot;)!<br><br>            let (data, _) = try! await URLSession.shared.data(from: url)<br><br>            let users = try! JSONDecoder().decode([User].self, from: data)<br><br>            self.users = users<br><br>            self.isLoading = false<br>        }<br>    }<br>}<br><br>struct ContentView: View {<br><br>    @StateObject private var vm = UserViewModel()<br><br>    var body: some View {<br><br>        VStack {<br><br>            if vm.isLoading {<br>                ProgressView()<br>            }<br><br>            List(vm.users) { user in<br>                Text(user.name)<br>            }<br><br>            Button(&quot;Reload&quot;) {<br>                vm.fetchUsers()<br>            }<br>        }<br>    }<br>}</pre><p>This one packs three separate bugs into a small block of code — a good question because candidates often only spot one.</p><ul><li><strong>No </strong><strong>@MainActor on the class or the </strong><strong>Task.</strong> The class isn&#39;t isolated to the main actor, and URLSession.shared.data(from:) isn&#39;t main-actor-isolated either. That means there&#39;s no compiler guarantee that self.users = users and self.isLoading = false run on the main thread. In this exact case it may often <em>happen</em> to work because Task {} inherits the calling context and SwiftUI is forgiving in simulator, but it&#39;s undefined behavior you&#39;re relying on, not a guarantee — and it&#39;s exactly the kind of thing Swift&#39;s actor isolation is supposed to catch at compile time.</li><li><strong>try! on both the network call and the decode.</strong> Any network failure (no connection, timeout, server error) or malformed/mismatched JSON crashes the app instantly. There&#39;s no error path at all — no way to show the user &quot;something went wrong&quot; or retry gracefully.</li><li><strong>No task management on repeated calls — a hidden race condition.</strong> Every tap of “Reload” spins up a brand-new unstructured Task, and nothing cancels the previous one. If a user taps &quot;Reload&quot; twice quickly, two requests race independently. If the <em>first</em> request happens to complete <em>after</em> the second one (out-of-order network responses are common), its stale data silently overwrites the newer result. isLoading has the same problem: the first task&#39;s isLoading = false can fire after the second task already set isLoading = true, causing the spinner to disappear mid-fetch.</li></ul><p>Correct Implementation</p><pre>@MainActor<br>final class UserViewModel: ObservableObject {<br>    @Published var users: [User] = []<br>    @Published var isLoading = false<br>    @Published var errorMessage: String?<br><br>    private var fetchTask: Task&lt;Void, Never&gt;?<br><br>    func fetchUsers() {<br>        fetchTask?.cancel()<br>        fetchTask = Task {<br>            isLoading = true<br>            defer { isLoading = false }<br>            do {<br>                let url = URL(string: &quot;https://api.example.com/users&quot;)!<br>                let (data, _) = try await URLSession.shared.data(from: url)<br>                let fetched = try JSONDecoder().decode([User].self, from: data)<br>                guard !Task.isCancelled else { return }<br>                users = fetched<br>                errorMessage = nil<br>            } catch {<br>                if !Task.isCancelled {<br>                    errorMessage = error.localizedDescription<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Understanding <em>why</em> this distinction matters — not just recognizing the syntax — is what separates a developer reciting rules from one who actually reasons about concurrency. That reasoning is exactly what these Seven question are designed to surface in an interview.</p><p><em>If you found this useful, consider following for more deep dives into Swift concurrency, SwiftUI architecture, and iOS interview prep.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=657a2a57e47e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Concurrency: A Deep Dive into actors and @Sendable]]></title>
            <link>https://medium.com/@ankit9deshwal9/swift-concurrency-a-deep-dive-into-actors-and-sendable-da6d293824b7?source=rss-718e92a470bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/da6d293824b7</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Ankit Kumar]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 09:34:02 GMT</pubDate>
            <atom:updated>2026-07-05T09:34:02.535Z</atom:updated>
            <content:encoded><![CDATA[<p>Data races ruined our apps for years. Here’s how Swift’s modern concurrency model finally solves the problem — cleanly, safely, and without all the boilerplate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AnGVHDelYMCPkWcbzOmdIA.jpeg" /></figure><p><strong>Picture this:</strong> your app has a shared counter object. Two async operations, A network response handler and a user-triggered update, both try to increment it at the exact same moment. The result? Undefined behaviour. A crash. A silent, maddening bug that only appears in production under load.</p><p>This is a data race, and for years iOS engineers dealt with them using Grand Central Dispatch, locks, semaphores, and a lot of defensive thinking. It worked. But it wasn’t safe by default — the compiler couldn’t warn you when you got it wrong.</p><p>Swift 5.5 changed everything. The language introduced a structured concurrency model built around two concepts that work beautifully together: actors, which protect shared mutable state, and @Sendable, which ensures data is safe to cross concurrency boundaries in the first place.</p><p>By the end of this article, you’ll understand both — not just in theory, but in the kind of practical, production code you write every day.</p><h3>The Problem: Data Races</h3><p>A data race occurs when two or more threads access the same memory location concurrently, and at least one of them is writing. There’s no built-in coordination — each thread races to read or write, and whoever gets there first “wins.” Except nobody really wins.</p><p>The danger</p><p>Data races are undefined behaviour. They can cause crashes, corrupted state, or silent incorrect results — and they’re notoriously hard to reproduce because the outcome depends on exact thread scheduling.</p><p>Here’s the classic culprit: a class-based counter shared across concurrent tasks.</p><pre>// ⚠️ NOT thread-safe — a classic data race waiting to happen<br>class Counter {<br>    var value: Int = 0<br>    func increment() {<br>            value += 1<br>        }<br>}<br>let counter = Counter()<br>// Launch 1000 concurrent tasks all hitting the same counter<br>await withTaskGroup(of: Void.self) { group in<br>    for _ in 0..&lt;1000 {<br>        group.addTask {<br>            counter.increment() // 💥 DATA RACE<br>        }<br>    }<br>}<br>// Expected: 1000. Actual: who knows? 742? 891? Crash?<br>print(counter.value)</pre><p>The problem is that value += 1 is not atomic. It&#39;s actually three operations: read the current value, add 1, write it back. Between those steps, another thread can swoop in and corrupt your state.</p><p>Before Swift concurrency, the fix was DispatchQueue serialisation or NSLock. They work, but the compiler couldn&#39;t enforce correct usage. You could forget a lock and ship a bug. Swift 5.5+ makes safety <em>the default</em>.</p><h3>Class vs Struct vs Actor</h3><p>Before diving deep into actors, it’s worth grounding ourselves in how they compare to the types we already know.</p><pre>| Feature.                             | Class                                       | Struct                                                 | Actor.                                                     |<br>| ------------------------------------ | ------------------------------------------- | ------------------------------------------------------ | ---------------------------------------------------------- |<br>| Semantics                            | Reference type                              | Value type                                             | Reference type                                             |<br>| Thread-safe by default               | No                                          | Partial                                                | Yes                                                        |<br>| Mutable shared state                 | Yes                                         | No (unless explicitly shared)                          | Isolated                                                   |<br>| Inheritance                          | Yes                                         | No                                                     | No                                                         |<br>| External access requires `await`     | No                                          | No                                                     | Yes                                                        |<br>| Compiler-enforced safety             | No                                          | No                                                     | Yes                                                        |<br>| Value copy on assignment             | No                                          | Yes                                                    | No                                                         |<br>| Best for                             | Legacy patterns,                            | Immutable data models,                                 | Shared mutable state,                                      |<br>|                                      | UIKit delegates, shared objects             | SwiftUI state, lightweight data                        | concurrency, thread-safe data access                       |<br>                                         </pre><p>The key insight: structs are safe because they’re copied — each task gets its own copy, so there’s no shared memory to race over. Actors are safe because they’re protected — only one task can access them at a time, enforced by the compiler.</p><h3>A quick look at each</h3><pre>// class — shared reference, no safety guarantees<br>class UserSession {<br>    var token: String = &quot;&quot;<br>}<br>// struct - copied on use, safe but not for shared state<br>struct UserProfile {<br>    let name: String<br>    let id: UUID<br>}<br>// actor - reference type with a protected mailbox<br>actor SessionManager {<br>    var token: String = &quot;&quot;<br>    func updateToken(_ newToken: String) {<br>        token = newToken // Safe - only one accessor at a time<br>    }<br>}</pre><h3>Understanding Actors</h3><p>An actor is a reference type — like a class — but with one critical difference: it has a built-in protection mechanism that ensures only one piece of code can access its state at any given moment.</p><p>Think of an actor as a locked room with a single door. Only one person can be inside at a time. If you want to read or change anything in the room, you have to wait your turn at the door.</p><p>That waiting is expressed in code as await. When you call a method on an actor from outside it, you&#39;re essentially queuing up at the door. Swift handles the scheduling, and the compiler enforces that you always use await.</p><pre>actor Counter {<br>    private var value: Int = 0<br>    func increment() {<br>        value += 1<br>    }<br>    func getValue() -&gt; Int {<br>        return value<br>    }<br>}<br>// Usage - note the await<br>let counter = Counter()<br>await counter.increment() // You&#39;re queuing up at the door<br>let current = await counter.getValue()<br>print(current) // Always accurate, never racey</pre><p>Notice that inside the actor, there are no await needed methods that are already running inside the protected context. It&#39;s only <em>external</em> callers that need to wait their turn.</p><p><strong>Key concept: Actor isolation</strong></p><p>Properties and methods of an actor can only be accessed in an async context from outside. The compiler will refuse to compile code that tries to access actor state synchronously from the outside. This is called actor isolation.</p><p>If you try to access an actor property without await, you&#39;ll get a compile error — not a runtime crash. This is the power: the mistake is caught before your code ever runs.</p><pre>actor BankAccount {<br>    var balance: Double = 1000.0<br>}<br>let account = BankAccount()<br>// ❌ Compiler error: &quot;Expression is &#39;async&#39; but is not marked with &#39;await&#39;&quot;<br>print(account.balance)<br>// ✅ Correct<br>Task {<br>    let bal = await account.balance<br>    print(bal)<br>}</pre><h3>Actor in Practice</h3><p>Let’s revisit our earlier broken counter — this time built as an actor. A thousand concurrent tasks, all incrementing, and it should always end at exactly 1000.</p><pre>actor SafeCounter {<br>    private var value: Int = 0<br>    func increment() {<br>            value += 1<br>        }<br>    var current: Int {<br>            value<br>        }<br>}<br>let counter = SafeCounter()<br>await withTaskGroup(of: Void.self) { group in<br>    for _ in 0..&lt;1000 {<br>        group.addTask {<br>            await counter.increment()<br>        }<br>    }<br>}<br>let final = await counter.current<br>print(final) // Always 1000. Guaranteed.</pre><p>Here’s a more realistic example: an image cache that multiple views might access concurrently.</p><pre>actor ImageCache {<br>   private var cache: [URL: UIImage] = [:]<br>    func image(for url: URL) -&gt; UIImage? {<br>        return cache[url]<br>    }<br>    func store(_ image: UIImage, for url: URL) {<br>        cache[url] = image<br>    }<br>    func imageOrFetch(for url: URL) async throws -&gt; UIImage {<br>        if let cached = cache[url] {<br>            return cached<br>        }<br>        let (data, _) = try await URLSession.shared.data(from: url)<br>        let image = UIImage(data: data)!<br>        cache[url] = image<br>        return image<br>    }<br>}<br>// Multiple views fetching concurrently - all perfectly safe<br>let imageCache = ImageCache()<br>async let img1 = imageCache.imageOrFetch(for: url1)<br>async let img2 = imageCache.imageOrFetch(for: url2)<br>let (i1, i2) = try await (img1, img2)</pre><p>No locks. No queues. No manual synchronisation. The actor guarantees that even if a hundred views all call imageOrFetch at once, there will never be duplicate fetches or corrupted cache state.</p><h3>Actor vs Grand Central Dispatch</h3><p>Many of us have years of muscle memory with GCD. Let’s compare how you’d handle the same problem using the old approach versus actors.</p><p>The task: a thread-safe data store that can be written to and read from concurrently.</p><h3>The GCD way</h3><pre>// The old way — functional, but fragile and verbose<br>class DataStoreGCD {<br>    private var data: [String: Any] = [:]<br>    private let queue = DispatchQueue(<br>        label: &quot;com.app.datastore&quot;,<br>        attributes: .concurrent<br>    )<br>   func getValue(for key: String) -&gt; Any? {<br>        return queue.sync {<br>            return data[key]<br>        }<br>    }<br>    func setValue(_ value: Any, for key: String) {<br>        queue.async(flags: .barrier) { // Easy to forget the .barrier!<br>            self.data[key] = value<br>        }<br>    }<br>    // Miss the .barrier flag? Silent data corruption. No compiler warning.<br>}</pre><h3>The actor way</h3><pre>// The modern way — compiler-enforced, readable, concise<br>actor DataStore {<br>    private var data: [String: Any] = [:]<br>    func getValue(for key: String) -&gt; Any? {<br>            return data[key]<br>        }<br>    func setValue(_ value: Any, for key: String) {<br>        data[key] = value // Automatic serialisation, no queue needed<br>    }<br>  }</pre><p>The actor version is not just shorter — it’s <em>safer by construction</em>. With GCD, you have to remember to use .barrier for writes, choose the right queue type, and avoid deadlocks. With actors, the compiler handles all of it. You can&#39;t accidentally misuse them.</p><p>Why actors win</p><p>GCD requires you to manually reason about every concurrent access. Actors make safety the default. The code expresses <em>what</em> you want, and Swift handles <em>how</em> to do it safely.</p><h3>Introduction to @Sendable</h3><p>Actors protect shared state <em>inside</em> a concurrency boundary. But what about the data being <em>passed between</em> tasks? What if you capture a mutable object in a closure and ship it off to a background thread?</p><p>This is where @Sendable comes in.</p><p>If an actor is the locked room, @Sendable is the security check on everything you’re allowed to carry through the door.</p><p>A @Sendable closure is one that&#39;s safe to send across concurrency boundaries. It can only capture values that are themselves safe to share — immutable values, value types, or types that implement the Sendable protocol.</p><p>Without this check, you could silently introduce data races even while using actors everywhere.</p><pre>// ⚠️ Dangerous: capturing a mutable class reference<br>class Config {<br>    var maxRetries: Int = 3<br>}<br>var config = Config()<br>Task {<br>    // config is a shared class reference - another thread could<br>    // modify maxRetries while this task is reading it<br>    print(config.maxRetries) // Potential data race on config<br>}<br>// Meanwhile, on the main thread:<br>config.maxRetries = 5 // 💥 Race condition</pre><p>Swift will warn you (and in strict concurrency mode, error on) closures that capture potentially unsafe values. The @Sendable attribute on a closure tells the compiler &quot;enforce safety rules on everything captured here.&quot;</p><h3>Using @Sendable Correctly</h3><p>The safest captures are immutable values and value types — they’re copied, so sharing them is inherently safe.</p><pre>// ✅ Safe: immutable let + value types = Sendable<br>let retries: Int = 3<br>let url: URL = URL(string: &quot;https://api.example.com&quot;)!<br>Task {<br>    // Both Int and URL are value types - totally safe to cross boundaries<br>    print(retries, url)<br>}<br>// ✅ Safe: @Sendable function type explicitly marks safety<br>func runInBackground(work: @Sendable () async -&gt; Void) {<br>    Task.detached {<br>        await work()<br>    }<br>}<br>// ✅ Safe: struct (value type) capture<br>struct Request {<br>    let id: UUID<br>    let endpoint: String<br>}<br>let request = Request(id: UUID(), endpoint: &quot;/users&quot;)<br>Task {<br>    // request is a value type - it&#39;s copied, not shared<br>    print(request.endpoint)<br>}</pre><h3>The Sendable protocol</h3><p>For your own types, you can explicitly declare them as safe to share by conforming to the Sendable protocol. Structs with all-Sendable stored properties automatically qualify. For classes, you need to reason carefully.</p><pre>// Struct with Sendable members — automatically Sendable<br>struct UserID: Sendable {<br>    let value: UUID<br>}<br>// Final class that is immutable after init - safe to mark Sendable<br>final class AppConfig: Sendable {<br>    let apiBaseURL: URL<br>    let timeout: TimeInterval<br>    init(baseURL: URL, timeout: TimeInterval) {<br>        self.apiBaseURL = baseURL<br>        self.timeout = timeout<br>    }<br>}<br>// ❌ This won&#39;t compile with strict concurrency - mutable var in class<br>class BadSendable: Sendable { // ⚠️ Compiler warning/error<br>    var count: Int = 0<br>}</pre><h3>Actor + @Sendable Together</h3><p>This is where the system really shines. Actors protect shared state. @Sendable protects the data flowing into and out of concurrency boundaries. Together, they form a complete safety model.</p><p>Here’s a real-world example: a request queue that processes jobs sent from anywhere in the app.</p><pre>struct Job: Sendable {<br>    let id: UUID<br>    let payload: String<br>}<br>actor JobQueue {<br>    private var queue: [Job] = []<br>    private var processed: Int = 0<br>    var processedCount: Int { processed }<br>    func enqueue(_ job: Job) { // Job is Sendable - safe to pass in<br>        queue.append(job)<br>    }<br>    func processNext() -&gt; Job? {<br>        guard !queue.isEmpty else { return nil }<br>        let job = queue.removeFirst()<br>        processed += 1<br>        return job<br>    }<br>}<br>// Submitting jobs from multiple concurrent contexts<br>let jobQueue = JobQueue()<br>await withTaskGroup(of: Void.self) { group in<br>    for i in 0..&lt;50 {<br>        group.addTask { // addTask accepts @Sendable closures<br>            let job = Job(id: UUID(), payload: &quot;Task \(i)&quot;)<br>            await jobQueue.enqueue(job)<br>        }<br>    }<br>}<br>let count = await jobQueue.processedCount<br>print(&quot;Enqueued 50 jobs safely&quot;)</pre><p>The Job struct is Sendable, so it&#39;s safe to pass into the actor from multiple tasks. The actor&#39;s internal queue is protected. The TaskGroup&#39;s closure is @Sendable, enforcing that everything captured is safe. Each layer reinforces the next.</p><p>The combination that matters</p><p>Use Sendable types to model data that travels between tasks. Use actor to protect shared state. Together, you get a system where data races are structurally impossible — not just unlikely.</p><h3>Common Mistakes</h3><h3>1. Forgetting await</h3><p>The most common beginner mistake. You’ll get a clear compile error, but it’s worth knowing why it’s required.</p><pre>actor Store { var items: [String] = [] }<br>let store = Store()<br>// ❌ Compile error - actor access requires async context<br>print(store.items)<br>// ✅ Correct<br>Task { print(await store.items) }</pre><h3>2. Capturing mutable state in @Sendable closures</h3><pre>class MutableConfig { var value: Int = 0 }<br>var config = MutableConfig()<br>// ❌ Captures a non-Sendable class - compiler warning in strict mode<br>Task.detached {<br>    print(config.value) // Unsafe: config isn&#39;t Sendable<br>}<br>// ✅ Use a Sendable snapshot instead<br>let snapshot = config.value // Capture the Int (Sendable), not the class<br>Task.detached {<br>    print(snapshot) // Safe<br>}</pre><h3>3. Overusing actors</h3><p>Not everything needs to be an actor. If a type is only ever accessed from one place, or its data is inherently immutable, use a struct instead. Actors have overhead — each external access is an async hop. Overusing them makes your code unnecessarily complex.</p><h3>4. Assuming actors solve all concurrency problems</h3><p>Actors protect against data races, but they don’t protect you from logical race conditions or deadlocks. If your actor calls out to another actor which calls back into the first, you can still create complex ordering bugs. Actors are a tool, not a silver bullet.</p><p>Watch out: reentrancy</p><p>Actors in Swift are reentrant. If an actor method awaits something externally, another task can access the actor while it&#39;s suspended. The state might have changed when execution resumes. Always re-read actor state after any await.</p><pre>actor ResourceLoader {<br>    var isLoading = false<br>    func load() async {<br>            guard !isLoading else { return }<br>            isLoading = true<br>            // ⚠️ While awaiting, another task might also enter here<br>            // and see isLoading = false (before this line ran)<br>            await performExpensiveLoad()<br>            // Re-check state after await - it might have changed<br>            isLoading = false<br>        }<br>}</pre><h3>When to Use What</h3><p>Here’s the practical decision guide. When you’re designing a type, ask yourself: does it need to be shared? Does it need to mutate?</p><h4>struct</h4><ul><li>Data models (User, Product)</li><li>No shared state needed</li><li>Value semantics are correct</li><li>Used in a single context</li><li>Should conform to Sendable</li></ul><h4>class</h4><ul><li>UIKit delegates &amp; objects</li><li>Needs reference semantics</li><li>Inherits from another class</li><li>Single-threaded only</li><li>Use @MainActor when on main thread</li></ul><h4>actor</h4><ul><li>Shared mutable state</li><li>Caches and data managers</li><li>Accessed from multiple tasks</li><li>Network request deduplication</li><li>Counters, queues, registries</li></ul><p>Quick rule</p><p>Start with struct. Add actor when you need shared mutable state across concurrent tasks. Use class when required by the framework (UIKit, etc.) and protect it with @MainActor where appropriate.</p><h3>@MainActor — a special actor worth knowing</h3><p>Swift includes a global actor called @MainActor that isolates code to the main thread. It&#39;s perfect for UI-related classes that must always run on the main thread — and it replaces the pattern of manually dispatching to DispatchQueue.main.</p><pre>@MainActor<br>class ProfileViewModel: ObservableObject {<br>    @Published var name: String = &quot;&quot;<br>    @Published var isLoading = false<br>    func fetchProfile() async {<br>            isLoading = true<br>            let profile = try? await loadFromNetwork()<br>            name = profile?.name ?? &quot;&quot;<br>            isLoading = false<br>            // All of this runs on main thread - no DispatchQueue.main.async!<br>        }<br>}</pre><h3>Wrapping Up</h3><p>Swift’s concurrency model is one of the most thoughtful additions the language has ever received. It doesn’t just give you new syntax — it makes an entire class of bugs structurally impossible.</p><h4>Key takeaways</h4><ul><li>Actors protect shared mutable state by serialising access — like a locked room where only one person enters at a time.</li><li>@Sendable ensures data is safe to pass across concurrency boundaries the security check at the door.</li><li>Actors requireawaitfrom external callers — this is enforced by the compiler, not just convention.</li><li>Not everything needs an actor. Reach forstructfirst when data doesn&#39;t need to be shared.</li><li>Actors are reentrant — always re-read state after anawaitinside an actor method.</li><li>@MainActorreplacesDispatchQueue.main.asyncfor UI-bound code.</li></ul><p>The hardest part of concurrent programming was never the technical machinery — it was maintaining the discipline to use it correctly everywhere, all the time. Swift’s concurrency model takes that burden off your shoulders and puts it on the compiler, where it belongs.</p><p>The rule of thumb: if your state is shared, wrap it in an actor. If your data is travelling between tasks, make it Sendable. Everything else is just writing normal Swift.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da6d293824b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Reactive Streams, Concurrency, and Async Task Management in Swift and iOS]]></title>
            <link>https://medium.com/@ankit9deshwal9/mastering-reactive-streams-concurrency-and-async-task-management-in-swift-and-ios-687ab5449eec?source=rss-718e92a470bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/687ab5449eec</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swit]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Ankit Kumar]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 11:38:35 GMT</pubDate>
            <atom:updated>2026-04-19T17:08:00.910Z</atom:updated>
            <content:encoded><![CDATA[<p>Why your iOS apps feel sluggish — and how modern Swift fixes it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7aKqem7zxTqlbmBA5cV8g.png" /></figure><p>If you’ve ever built an iOS app, you’ve probably hit the classic performance wall: the UI freezes while fetching data from the network, or a heavy computation blocks the main thread and makes the app unresponsive. Users hate it. Apple’s Human Interface Guidelines are crystal clear — apps must feel <em>instant</em>.</p><p>That’s where <strong>reactive streams</strong>, <strong>Swift concurrency</strong>, and <strong>asynchronous task management</strong> come in. They let you write non-blocking, responsive code that scales beautifully. In this article, we’ll explore these concepts with real iOS examples, clean Swift code, and practical guidance on when to use each tool.</p><p><strong>The Problem: Blocking Code in iOS</strong></p><p>Traditional synchronous code runs everything on the main thread by default:</p><pre>// ❌ This blocks the UI<br>let data = try await fetchUsersFromAPI()  // Wait... no, this is async, but imagine it was sync<br>updateTableView(with: data)</pre><p>Network calls, JSON parsing, database queries — any of these can take hundreds of milliseconds. On the main thread, that means janky scrolling, frozen animations, or the dreaded “beachball” on macOS Catalyst apps.</p><p>Non-blocking approaches solve this by:</p><ul><li>Moving work off the main thread</li><li>Letting the UI stay responsive</li><li>Handling data <em>as it arrives</em> instead of waiting for everything</li></ul><p>Enter <strong>reactive programming</strong> and <strong>Swift’s modern concurrency tools</strong>.</p><h4><strong>What Are Reactive Streams?</strong></h4><p>Reactive programming is a declarative style where you describe <em>what</em> should happen when data changes, not <em>how</em> to fetch and update it step-by-step.</p><p>A <strong>reactive stream</strong> is a pipeline that pushes values over time. Think of it like a YouTube live stream instead of a static video file:</p><ul><li><strong>Publisher</strong> = the source that emits values (or errors)</li><li><strong>Subscriber</strong> = the consumer that receives values and decides what to do</li><li><strong>Data flow</strong> = values flow downstream automatically</li><li><strong>Backpressure</strong> = the subscriber can tell the publisher, “slow down, I can’t keep up” (crucial for memory management)</li></ul><p>This model shines in iOS for live search, real-time UI updates, and combining multiple data sources.</p><h3>Concurrency in Swift: From GCD to Async/Await</h3><h4>The Old Way: Grand Central Dispatch (GCD)</h4><p>Before Swift 5.5, we used queues:</p><pre>DispatchQueue.global(qos: .userInitiated).async {<br>    let data = fetchData()  // background work<br>    DispatchQueue.main.async {<br>        self.updateUI(with: data)<br>    }<br>}</pre><p>It works, but nesting callbacks (the “pyramid of doom”) quickly becomes unreadable, especially with error handling and cancellation.</p><h3>The Modern Way: Swift Concurrency (async/await, Task, TaskGroup)</h3><p>Since Swift 5.5 (iOS 15+), we have structured concurrency:</p><pre>Task {<br>    do {<br>        let data = try await fetchDataFromAPI()  // suspension point, non-blocking<br>        await MainActor.run { self.updateUI(with: data) }<br>    } catch {<br>        // handle error<br>    }<br>}</pre><p><strong>Key differences</strong>:</p><pre>Feature              |   GCDSwift                   |   Concurrency<br>Readability          |   Callbacks &amp; nesting        |  Linear async/await code<br>Cancellation         |   Manual                     |  Automatic via Task cancellation<br>Structured           |   No                         |  Yes (TaskGroup, withThrowingTaskGroup)<br>Actor isolation      |   None(race conditions easy) |  Built-in safety (@MainActor)</pre><p><strong>Concurrency ≠ Parallelism</strong></p><ul><li><strong>Concurrency</strong>: Multiple tasks <em>appear</em> to run at the same time by switching rapidly (great for UI responsiveness).</li><li><strong>Parallelism</strong>: Tasks actually run <em>simultaneously</em> on multiple CPU cores (useful for heavy CPU work like image processing).</li></ul><p><strong>iOS example</strong>:</p><ul><li>Concurrency: A view model fetches user profile + posts + friends list concurrently using async let.</li><li>Parallelism: A TaskGroup processes 20 large photos in parallel on background threads.</li></ul><pre>// Concurrency + parallelism in one go<br>async let profile = fetchProfile()<br>async let posts = fetchPosts()<br>async let friends = fetchFriends()<br><br>let (p, po, f) = try await (profile, posts, friends)</pre><p>Combine: Reactive Streams Done Right in Apple’s Ecosystem</p><p><strong>Combine</strong> (introduced iOS 13) is Apple’s native reactive framework. It implements reactive streams using three core protocols:</p><ul><li>Publisher: Emits values over time</li><li>Subscriber: Receives values</li><li>Operator: Transforms the stream (.map, .filter, .debounce, etc.)</li></ul><h3>Simple Combine Example: Live Search</h3><pre>import Combine<br><br>class SearchViewModel: ObservableObject {<br>    @Published var searchText = &quot;&quot;<br>    @Published var results: [User] = []<br>    <br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br>    <br>    init() {<br>        $searchText<br>            .debounce(for: 0.3, scheduler: RunLoop.main)  // backpressure in action<br>            .removeDuplicates()<br>            .flatMap { text in<br>                self.searchAPI(query: text)               // returns AnyPublisher<br>            }<br>            .receive(on: DispatchQueue.main)<br>            .sink { [weak self] users in<br>                self?.results = users<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br>}</pre><p>Backpressure is handled automatically — debounce prevents flooding the API with every keystroke.</p><h3>Combine vs RxSwift</h3><p>Combine is lighter, integrates perfectly with SwiftUI (@Published), and is maintained by Apple. RxSwift offers more operators and has a larger community, but requires an extra dependency. For most new iOS apps, <strong>Combine wins</strong>.</p><h3>Swift’s AsyncStream: Lightweight Reactive Streams Without Combine</h3><p>Sometimes you don’t need the full power (and complexity) of Combine. Enter AsyncStream (iOS 15+, part of Swift Concurrency).</p><p>AsyncStream conforms to AsyncSequence, so you can use it with for await loops — just like AsyncSequence.</p><h3>Why AsyncStream?</h3><ul><li>Simple custom streams without operators</li><li>Built-in cancellation support</li><li>Fine-grained control over buffering (backpressure)</li></ul><h3>Creating and Using an AsyncStream</h3><pre>// 1. Create the stream<br>let locationStream = AsyncStream&lt;CLLocationCoordinate2D&gt; { continuation in<br>    let manager = CLLocationManager()<br>    manager.delegate = ... // or use a wrapper<br>    <br>    // Yield values as they arrive<br>    continuation.yield(newLocation)<br>    <br>    // When done or cancelled<br>    continuation.onTermination = { _ in<br>        manager.stopUpdatingLocation()<br>    }<br>}<br><br>// 2. Consume it<br>Task {<br>    for await location in locationStream {<br>        print(&quot;New location: \(location)&quot;)<br>        // Update UI safely on MainActor<br>    }<br>}</pre><h3>The Magic of yield</h3><p>continuation.yield(value) emits a value to anyone awaiting the stream. It’s non-blocking and respects the buffering policy.</p><h4>BufferingPolicy: Controlling Backpressure</h4><pre>let bufferedStream = AsyncStream&lt;Int&gt;(bufferingPolicy: .bufferingNewest(5)) { continuation in<br>    // Producer keeps yielding<br>    for i in 1...100 {<br>        continuation.yield(i)<br>        try? await Task.sleep(for: .milliseconds(10))<br>    }<br>    continuation.finish()  // signals completion<br>}</pre><p>Options:</p><ul><li>.<em>unbounded</em> → Never drops values (risk of memory explosion)</li><li>.<em>bufferingNewest(n)</em> → Keeps only the latest n values (perfect for live location or stock prices)</li><li>.<em>bufferingOldest(n)</em> → Keeps the oldest n values (good for logs)</li></ul><h3>Handling Cancellation &amp; Completion</h3><pre>let cancellableTask = Task {<br>    for await value in myStream {<br>        if Task.isCancelled { break }<br>        // process value<br>    }<br>}<br><br>// Later:<br>cancellableTask.cancel()  // Automatically triggers onTermination</pre><p><strong>When to choose AsyncStream</strong>:</p><ul><li>Simple one-way data flows (location updates, WebSocket messages, sensor data)</li><li>You want async/await syntax without learning Combine operators</li><li>Replacing callback closures or delegates</li></ul><h3>Real-World iOS Use Cases</h3><pre><br><br>Use Case                      |   Best Tool             |      Why  <br>Live search/autocomplete      |   Combine               |  Powerful operators (debounce, flatMap)<br>Real-time UI updates.         |   Combine + @Published  |  Zero-boiler-plate SwiftUI binding<br>WebSocket / live location.    |   AsyncStream.          |  Simple for await loop + buffering control<br>Background image processing.  |   TaskGroup             |  Parallelism on background queues<br>API calls with refresh        |   async/await + Task    |  Clean, cancellable, structured<br>Legacy delegate callbacks.    |   AsyncStream           |  Bridge old code to modern concurrency</pre><h3>Benefits and Trade-offs</h3><p><strong>Benefits</strong>:</p><ul><li><strong>Responsiveness</strong>: Main thread stays free → buttery-smooth 120 fps animations</li><li><strong>Cleaner code</strong>: Linear, readable async flows instead of nested callbacks</li><li><strong>Scalability</strong>: Automatic cancellation, structured error handling, and backpressure</li><li><strong>Testability</strong>: Streams and tasks are easy to mock</li></ul><p><strong>Trade-offs</strong>:</p><ul><li>Learning curve (especially Combine operators)</li><li>Debugging can be trickier (“where did this value come from?”)</li><li>Risk of over-engineering simple screens</li><li>iOS 15+ requirement for full Swift Concurrency (though backports exist)</li></ul><h3>Choosing the Right Tool: Practical Guidance</h3><ul><li><strong>Use async/await + Task</strong> for straightforward asynchronous work (network calls, file I/O).</li><li><strong>Choose Combine</strong> when you have complex data transformations, multiple sources, or heavy SwiftUI integration.</li><li><strong>Reach for AsyncStream</strong> when you need a simple custom stream, fine-grained buffering, or want to stay in a pure async/await world.</li><li><strong>Stick with GCD</strong> only for very low-level performance tweaks or supporting iOS 14 and below.</li></ul><p>Start small. Refactor one screen at a time. Your users (and future self) will thank you when the app feels instantly responsive even on slow networks.</p><p>Ready to level up your iOS concurrency game? Drop a comment with the trickiest async problem you’ve faced — I’d love to help refactor it together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=687ab5449eec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Swift Concurrency: Task Termination, Subtasks, and Cancellation]]></title>
            <link>https://medium.com/@ankit9deshwal9/mastering-swift-concurrency-task-termination-subtasks-and-cancellation-689a5a48ce53?source=rss-718e92a470bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/689a5a48ce53</guid>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Ankit Kumar]]></dc:creator>
            <pubDate>Tue, 20 Jan 2026 19:42:21 GMT</pubDate>
            <atom:updated>2026-01-20T19:42:21.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7aKqem7zxTqlbmBA5cV8g.png" /></figure><p>Swift Concurrency, introduced in Swift 5.5, revolutionized how developers handle asynchronous and parallel code on Apple platforms. It provides a modern, safe, and efficient way to write concurrent code without the pitfalls of traditional threading models. In this blog post, we’ll dive deep into task termination and cancellation, with a special focus on how these concepts apply to subtasks. We’ll blend theory with practical Swift code examples to help you build responsive and robust apps. Whether you’re transitioning from GCD or callbacks, or just deepening your async/await knowledge, this guide has you covered.</p><h4>Introduction to Swift Concurrency</h4><p>Swift Concurrency is built around the “<em>async/await”</em> syntax, which allows you to write asynchronous code that looks and feels synchronous. At its core, it leverages tasks as the fundamental unit of concurrency. Tasks are lightweight, cooperative units of work that can run concurrently, managed by the system’s executor (often backed by threads, but abstracted away from the developer).</p><h4>Structured vs. Unstructured Concurrency</h4><ul><li><strong>Structured Concurrency</strong>: This is the recommended approach in Swift. It ensures that tasks have a clear hierarchy and lifecycle. Tools like TaskGroup and AsyncSequence help manage child tasks, automatically propagating errors and cancellations. Structured concurrency prevents “task leaks” by ensuring all subtasks complete before the parent finishes.</li><li><strong>Unstructured Concurrency</strong>: This involves creating standalone tasks without a parent-child relationship, using “<em>Task.detached”</em> or plain “<em>Task { … }</em>”. It’s more flexible but riskier, as you must manually manage cancellation and completion to avoid orphaned tasks.</li></ul><h4>Difference Between async/await and Classic Threading</h4><p>Classic threading <em>(e.g., via Thread or Grand Central Dispatch/GCD)</em> involves manually managing threads, locks, and queues, which can lead to race conditions, deadlocks, and priority inversion. Swift’s <em>async/await</em>, on the other hand:</p><ul><li>Uses cooperative scheduling: Tasks yield control at suspension points (e.g., await), allowing the system to optimize thread usage.</li><li>Avoids thread explosion: The runtime reuses a pool of threads efficiently.</li><li>Integrates seamlessly with actors for data isolation, reducing the need for manual synchronization.</li></ul><p>In essence, <em>async/await</em> focuses on <em>what</em> to do asynchronously, while classic threading focuses on <em>how</em> (e.g., which queue or thread).</p><h4>Ways to Achieve Concurrency in Swift</h4><p>Swift offers several mechanisms for concurrency. Here’s a breakdown with code examples:</p><ol><li><strong>Async Functions and Await</strong>: The simplest way for sequential asynchronous operations.</li></ol><pre>func fetchData() async throws -&gt; Data {<br>    let url = URL(string: &quot;https://example.com&quot;)!<br>    let (data, _) = try await URLSession.shared.data(from: url)<br>    return data<br>}<br><br>// Usage<br>Task {<br>    do {<br>        let data = try await fetchData()<br>        print(&quot;Data fetched: \(data.count) bytes&quot;)<br>    } catch {<br>        print(&quot;Error: \(error)&quot;)<br>    }<br>}</pre><p><strong>2.</strong> <strong>Standalone Tasks (Unstructured):</strong> For fire-and-forget or detached work.</p><pre>let task = Task {<br>    print(&quot;Running in a standalone task&quot;)<br>    try await Task.sleep(for: .seconds(1))<br>    return &quot;Done&quot;<br>}<br><br>// Or detached for no inheritance<br>let detachedTask = Task.detached {<br>    print(&quot;Detached task running independently&quot;)<br>}</pre><p><strong>3.</strong> <strong>Task Groups (Structured):</strong> For parallel execution of subtasks with automatic management.</p><pre><br>Task {<br>    // Parent task<br>    let parentTask = Task {<br>        print(&quot;Parent task started&quot;)<br>        <br>        await withTaskGroup(of: String.self) { group in<br>            // Add multiple subtasks<br>            for i in 1...5 {<br>                group.addTask {<br>                    // Simulate async work<br>                    do {<br>                        print(&quot;Subtask \(i) started&quot;)<br>                        try await Task.sleep(for: .seconds(i)) // simulate varying workload<br>                        return &quot;Subtask \(i) finished&quot;<br>                    } <br>                }<br>            }<br>            // Collect results as they complete<br>            for await result in group {<br>                print(result)<br>            }<br>        }<br>        print(&quot;Parent task completed&quot;)<br>    }<br>}</pre><p>4. <strong>Actors:</strong> For concurrent access to shared state.</p><pre><br>// Define an actor to safely manage shared state<br>actor Counter {<br>    private(set) var value = 0<br><br>    func increment() {<br>        value += 1<br>        print(&quot;Incremented to \(value)&quot;)<br>    }<br><br>    func reset() {<br>        value = 0<br>        print(&quot;Reset to \(value)&quot;)<br>    }<br>}<br><br>// Create a shared actor instance<br>let counter = Counter()<br><br>// Function to simulate concurrent access<br>func performConcurrentIncrements() async {<br>    print(&quot;Starting concurrent tasks...&quot;)<br><br>    await withTaskGroup(of: Void.self) { group in<br>        // Task 1<br>        group.addTask {<br>            for _ in 1...5 {<br>                await counter.increment()<br>                try? await Task.sleep(for: .milliseconds(100))<br>            }<br>        }<br><br>        // Task 2<br>        group.addTask {<br>            for _ in 1...5 {<br>                await counter.increment()<br>                try? await Task.sleep(for: .milliseconds(150))<br>            }<br>        }<br>    }<br><br>    // Access the final value<br>    let finalValue = await counter.value<br>    print(&quot;Final counter value: \(finalValue)&quot;)<br>}<br><br>// Run the concurrent tasks<br>Task {<br>    await performConcurrentIncrements()<br>}</pre><p>5. <strong>Async Sequences: </strong>For streaming data concurrently (e.g., with AsyncStream).</p><pre>let stream = AsyncStream&lt;Int&gt; { continuation in<br>    Task {<br>        for i in 1...5 {<br>            continuation.yield(i)<br>            try await Task.sleep(for: .seconds(1))<br>        }<br>        continuation.finish()<br>    }<br>}<br><br>for await value in stream {<br>    print(value)<br>}</pre><p>These tools cover most concurrency needs, from simple async calls to complex parallel workflows.</p><h4>Task Termination</h4><p>Most developers know how to add a Task when some work needs to happen asynchronously. We use it for API calls, background processing, or heavy computations without blocking the UI. Easy enough.</p><blockquote>But here’s the real question — <strong>what happens when that task needs to stop?</strong></blockquote><p>In Swift Concurrency, task termination is <strong>cooperative</strong>. Tasks don’t get force-killed. Instead, they’re <em>politely asked</em> to stop via cancellation. This gives your code a chance to clean up safely and prevents abrupt interruptions.</p><blockquote>Now think about this:</blockquote><ul><li>Are you actually handling task cancellation?</li><li>Do your tasks check whether they’ve been cancelled?</li><li>And if your task spawns <strong>subtasks</strong>, do they stop too — or keep running silently in the background?</li></ul><p>These are the kinds of details that often get overlooked, but they can make the difference between a smooth, efficient app and one that leaks work, battery, or memory.</p><h4>Canceling a Running Task</h4><p>You cancel a task using <em>task.cancel()</em>. This sets the task’s <em>isCancelled</em> flag to <em>true</em> but doesn’t immediately stop execution. The task must check for cancellation and respond accordingly.</p><h4>What Happens When a Task is Cancelled?</h4><ul><li>The task enters a “cancelled” state.</li><li>Any awaiting points (e.g., await) may throw CancellationError if the task checks for it.</li><li>Subtasks (in structured concurrency) inherit the cancellation automatically.</li><li>The task continues running until it hits a cancellation check or completes naturally.</li></ul><h4>Best Practices for Checking Task.isCancelled</h4><ul><li>Use Task.checkCancellation() in loops or long-running operations to throw CancellationError if cancelled.</li><li>Check Task.isCancelled for manual handling without throwing.</li><li>Place checks at logical suspension points to allow a graceful exit.</li></ul><h4>Here’s an example:</h4><pre>let task = Task {<br>    for i in 1...5 {<br>        try Task.checkCancellation()  // Throws if cancelled<br>        print(&quot;Running step \(i)&quot;)<br>        try await Task.sleep(nanoseconds: 1_000_000_000)  // 1 second<br>    }<br>    print(&quot;Task completed&quot;)<br>}<br><br>// Simulate delay then cancel<br>try await Task.sleep(nanoseconds: 2_500_000_000)<br>task.cancel()</pre><p>In this code, after cancellation, the loop will throw at the next <em>checkCancellation()</em>, preventing further steps.</p><h4>Subtasks and Cancellation</h4><p>In structured concurrency, subtasks are tied to their parent. Cancellation propagates automatically, making management easier.</p><h4>Inheritance of Cancellation</h4><p>When a parent task is cancelled, all child tasks in a <em>TaskGroup</em> or via <em>addTask</em> inherit the cancellation. They won’t start if added after cancellation, and running ones can check and respond.</p><h4>Explicitly Canceling Subtasks</h4><p>While inheritance handles most cases, you can cancel individual child tasks if needed (though rare in structured setups). In unstructured scenarios, manual propagation is key.</p><p>Example with subtasks:</p><pre>let parentTask = Task {<br>    await withTaskGroup(of: Void.self) { group in<br>        for i in 1...3 {<br>            group.addTask {<br>                print(&quot;Subtask \(i) started&quot;)<br>                try Task.checkCancellation()<br>                try await Task.sleep(nanoseconds: 2_000_000_000)  // 2 seconds<br>                print(&quot;Subtask \(i) finished&quot;)<br>            }<br>        }<br>        await group.waitForAll()  // Wait for children<br>    }<br>    print(&quot;Parent finished&quot;)<br>}<br><br>// Cancel parent after delay<br>try await Task.sleep(nanoseconds: 1_000_000_000)<br>parentTask.cancel()</pre><p>Here, cancelling the parent will cause subtasks to throw at checkCancellation() or await points.</p><h4>Use Cases to Consider</h4><p>Let’s explore some usecase.</p><h3>Case 1: Subtask Inherits Cancellation and is Automatically Stopped</h3><p>In a network fetch with parallel downloads, cancelling the parent stops all children:</p><pre>let downloadTask = Task {<br>    try await withThrowingTaskGroup(of: Data.self) { group in<br>        for url in urls {  // Assume urls is an array<br>            group.addTask {<br>                try Task.checkCancellation()<br>                let (data, _) = try await URLSession.shared.data(from: url)<br>                return data<br>            }<br>        }<br>        var results: [Data] = []<br>        for try await data in group {<br>            results.append(data)<br>        }<br>        return results<br>    }<br>}<br><br>// Cancel after some time<br>downloadTask.cancel()  // Children inherit and stop at checks</pre><h3>Case 2: Subtask Continues Despite Parent Cancellation, and Manual Propagation</h3><p>In unstructured concurrency, cancellation doesn’t propagate automatically. Use manual checks or link tasks.</p><p>For continuation despite cancellation (e.g., background cleanup):</p><pre>let parent = Task {<br>    print(&quot;Parent starting&quot;)<br>    let child = Task.detached {  // Detached, no auto-propagation<br>        for _ in 1...10 {<br>            if Task.isCancelled {<br>                print(&quot;Child detected cancellation manually&quot;)<br>                return<br>            }<br>            try await Task.sleep(for: .seconds(1))<br>            print(&quot;Child working&quot;)<br>        }<br>    }<br>    try await Task.sleep(for: .seconds(3))<br>    print(&quot;Parent finishing&quot;)<br>}<br><br>parent.cancel()  // Child continues unless it checks</pre><p>To manually propagate:</p><pre>let parent = Task {<br>    let child = Task {<br>        try Task.checkCancellation()  // Will throw if parent cancelled<br>        // Work...<br>    }<br>    // Manually propagate if needed<br>    if Task.isCancelled {<br>        child.cancel()<br>    }<br>    try await child.value<br>}<br>parent.cancel()  // Child gets cancelled manually</pre><h3>Best Practices for Developers</h3><ul><li><strong>Always Check for Cancellation in Loops</strong>: Use <em>Task.checkCancellation()</em> or <em>Task.isCancelled</em> in long-running or iterative code to respond promptly.</li><li><strong>Prefer Structured Concurrency</strong>: Leverage <em>withTaskGroup</em> or <em>withThrowingTaskGroup</em> to automatically handle subtasks, errors, and cancellations.</li><li><strong>Understand TaskGroup Behavior</strong>: When a parent is cancelled, <em>addTask</em> after cancellation fails, and awaiting children throws <em>CancellationError</em>. Child tasks in groups are cancelled when the group exits early.</li><li><strong>Avoid Orphaned Tasks</strong>: In unstructured setups, ensure tasks are awaited or their results handled to prevent leaks. Use <em>Task.detached</em> sparingly.</li></ul><p>Following these keeps your app responsive and prevents resource waste.</p><h4>Conclusion</h4><p>Mastering task termination and cancellation in Swift Concurrency is key to writing efficient, user-friendly apps. We’ve covered structured and unstructured approaches, cancellation mechanics, subtask inheritance, and practical examples to handle real-world scenarios. Remember: cooperative cancellation empowers you to build systems that gracefully handle interruptions, whether from user actions or system events.</p><p>By prioritizing checks, structured hierarchies, and mindful task management, you’ll avoid common pitfalls like hanging operations or memory leaks. Dive into these concepts in your next project — your apps will be more robust and performant for it. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=689a5a48ce53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Property Wrappers: Mastering Data Flow in 2025]]></title>
            <link>https://medium.com/@ankit9deshwal9/swiftui-property-wrappers-mastering-data-flow-in-2025-5157cbf4ed7f?source=rss-718e92a470bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5157cbf4ed7f</guid>
            <dc:creator><![CDATA[Ankit Kumar]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 16:58:10 GMT</pubDate>
            <atom:updated>2025-12-23T16:58:10.403Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7aKqem7zxTqlbmBA5cV8g.png" /></figure><p>SwiftUI has transformed iOS (and multi-platform) development since 2019, delivering declarative UIs that react magically to data changes. The real engine behind this magic? <strong>Property wrappers</strong>.</p><p>These Swift features — @State, @Binding, @Observable, @Bindable, @Environment, plus the classic trio of @StateObject, @ObservedObject, and @EnvironmentObject — manage state, observation, and data propagation elegantly.</p><p>Whether you’re building your first app or scaling a large codebase, understanding when to use each wrapper (and when to retire the older ones) is key to writing clean, performant, and maintainable code.</p><p>If you’ve ever debugged a view that refuses to update, struggled with prop drilling, or wondered how the <strong>Observation</strong> framework has simplified everything since iOS 17, this guide is for you.</p><p>We’ll cover all major property wrappers, including the legacy ones, with code examples and clear recommendations as of December 2025. By the end, you’ll know exactly which tool to reach for in modern SwiftUI development.</p><p>Let’s get into it.</p><h4>The Foundation: How Property Wrappers Power SwiftUI’s Reactivity</h4><p>Property wrappers encapsulate logic around stored properties, telling SwiftUI when to observe changes and trigger redraws.</p><p>The ecosystem rests on three pillars:</p><ul><li><strong>Local state</strong> — @State for values owned by the view</li><li><strong>Shared observation</strong> — @Observable classes (iOS 17+) for models</li><li><strong>Environment injection</strong> — @Environment for hierarchy-wide access</li></ul><p>Since iOS 17, the <strong>Observation</strong> framework enables <em>fine-grained</em> tracking: SwiftUI redraws only the parts of your UI that depend on changed properties — huge performance win compared to full object invalidation in older @Published / ObservableObject setups.</p><h4>@State: The Everyday Hero for Local Data</h4><p>Use @State for values owned and mutated exclusively by the view. Ideal for primitives, structs, and — crucially since iOS 17 — <strong>@Observable</strong> classes.</p><pre>struct CounterView: View {<br>    @State private var count = 0<br>    <br>    var body: some View {<br>        VStack {<br>            Text(&quot;Count: \(count)&quot;)<br>            Button(&quot;Increment&quot;) { count += 1 }<br>        }<br>    }<br>}</pre><p>Modern pattern with @Observable class (strongly recommended in 2025):</p><pre>@Observable<br>class ShoppingCart {<br>    var items: [String] = []<br>    var total: Double = 0.0<br>}<br><br>struct CartView: View {<br>    @State private var cart = ShoppingCart()<br>    <br>    var body: some View {<br>        List(cart.items, id: \.self) { item in<br>            Text(item)<br>        }<br>        Button(&quot;Add Apple&quot;) {<br>            cart.items.append(&quot;Apple&quot;)<br>            cart.total += 1.99<br>        }<br>    }<br>}</pre><p>@State preserves the instance across view recreations and provides automatic bindings ($cart.total works directly).</p><h4>@Binding: Enabling Two-Way Communication</h4><p>When a child needs to read <strong>and</strong> modify a parent’s value, use @Binding.</p><pre>struct ToggleSwitch: View {<br>    @Binding var isOn: Bool<br>    <br>    var body: some View {<br>        Toggle(&quot;Dark Mode&quot;, isOn: $isOn)<br>    }<br>}<br><br>struct Settings: View {<br>    @State private var darkMode = false<br>    <br>    var body: some View {<br>        ToggleSwitch(isOn: $darkMode)<br>    }<br>}</pre><p>For @Observable objects passed from outside, use @Bindable for bindings:</p><pre>struct EditNameView: View {<br>    @Bindable var user: UserProfile  // UserProfile is @Observable<br>    <br>    var body: some View {<br>        TextField(&quot;Name&quot;, text: $user.name)<br>    }<br>}</pre><h3>@Observable: The Modern Model Backbone (iOS 17+)</h3><p>Mark classes with @Observable — no more @Published boilerplate.</p><pre>@Observable<br>class UserProfile {<br>    var name = &quot;Jordan&quot;<br>    var avatarURL: URL?<br>}</pre><p>Store owned instances with @State (replacing @StateObject):</p><pre>@State private var profile = UserProfile()</pre><p>Pass for read-only observation: just the reference (ChildView(profile: profile)). SwiftUI tracks accessed properties automatically.</p><p>This is the preferred pattern in late 2025 — simpler, faster, and Apple’s recommended direction.</p><h4>Legacy Wrappers: When You Still Need Them</h4><p><strong>@StateObject</strong> Use for <strong>creating</strong> legacy ObservableObject classes (with @Published). Ensures the instance survives view recreations.</p><pre>@StateObject private var vm = LegacyViewModel()  // LegacyViewModel: ObservableObject</pre><p><strong>Migrate to</strong> @State + @Observable whenever possible.</p><p><strong>@ObservedObject</strong> For <strong>receiving</strong> legacy ObservableObject instances passed down. Avoid creating with it (risks recreation/loss of state).</p><p>In modern code: rarely needed — just pass @Observable objects directly.</p><p><strong>@EnvironmentObject</strong> Legacy way to share ObservableObject deep in the hierarchy.</p><pre>@EnvironmentObject var settings: LegacySettings</pre><p>Provide with</p><pre>.environmentObject(settings)</pre><p><strong>Still useful</strong> for compatibility or mixed codebases, but prefer the new @Environment for new work.</p><h4>@Environment: Clean, Type-Safe Sharing (The 2025 Favorite)</h4><p>Inject @Observable instances with .environment() and access via @Environment(Type.self).</p><pre>@Observable<br>class ThemeManager {<br>    var current: Theme = .light<br>}<br><br>struct ThemedContent: View {<br>    @Environment(ThemeManager.self) private var themeManager<br>    <br>    var body: some View {<br>        Text(&quot;Hello&quot;)<br>            .foregroundStyle(themeManager.current.accentColor)<br>    }<br>}</pre><pre>// How to provide the environment object <br>ContentView()<br>    .environment(ThemeManager())</pre><p>Advantages: type-safe, no runtime crashes if missing (provide defaults), no need for ObservableObject protocol. This is the go-to for shared data in modern apps.</p><h3>Quick Decision Guide (December 2025 Edition)</h3><ul><li><strong>Local primitive/struct</strong> → @State</li><li><strong>Owned @Observable class (new code)</strong> → @State + @Observable</li><li><strong>Owned legacy ObservableObject</strong> → @StateObject (migrate soon)</li><li><strong>Pass &amp; mutate value to child</strong> → @Binding (values) or @Bindable (@Observable)</li><li><strong>Read-only shared @Observable</strong> → Pass directly (no wrapper)</li><li><strong>App-wide / deep hierarchy (new)</strong> → @Environment(Type.self) + .environment()</li><li><strong>Legacy shared ObservableObject</strong> → @EnvironmentObject</li><li><strong>Receiving legacy object</strong> → @ObservedObject (rare)</li></ul><h3>Conclusion: Embrace the Modern Path</h3><p>In late 2025, SwiftUI state management has never been cleaner. The <strong>@Observable</strong> + <strong>@State</strong> / <strong>@Environment</strong> / <strong>@Bindable</strong> combo delivers simpler syntax, better performance, and fewer bugs than the original ObservableObject system.</p><p>If your codebase still leans on @StateObject, @ObservedObject, and @EnvironmentObject — that’s fine for compatibility. But for new features or refactors, migrate to the Observation framework patterns. You’ll thank yourself later.</p><p>Start small: pick one view model, add @Observable, swap @StateObject for @State, and watch the code shrink while performance improves.</p><p>SwiftUI keeps evolving — and state management has become one of its strongest features. Happy building!</p><p>What’s your current mix — full modern Observation or still some legacy wrappers? Share in the comments! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5157cbf4ed7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Custom Accordion Component in SwiftUI: Part 2]]></title>
            <link>https://medium.com/@ankit9deshwal9/building-a-custom-accordion-component-in-swiftui-part-2-1cf815ff09f0?source=rss-718e92a470bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cf815ff09f0</guid>
            <dc:creator><![CDATA[Ankit Kumar]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 14:04:50 GMT</pubDate>
            <atom:updated>2025-08-25T14:33:32.551Z</atom:updated>
            <content:encoded><![CDATA[<h4>Expandable Lists with Smooth Animations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7aKqem7zxTqlbmBA5cV8g.png" /></figure><p>As SwiftUI developers, we often need to present information in a compact, user-friendly way. Accordions — those expandable/collapsible sections — are perfect for FAQs, settings panels, or detailed lists where space is at a premium. In this article, we’ll dive into a custom implementation of an accordion view called SFAccordionView. This component is built entirely in SwiftUI, featuring smooth animations, dynamic height calculation for content, and even a typewriter effect for expanding descriptions.</p><p>Whether you’re building an app with dense content or just want to level up your UI skills, this guide will walk you through the code, explain key concepts, and show you how to integrate it into your projects. Let’s get started!</p><h3>What is an Accordion in UI Design?</h3><blockquote>You can also refer to my previous blog about the Accordion view. <br>link: <a href="https://medium.com/@ankit9deshwal9/how-to-build-an-expandable-list-view-in-swiftui-with-states-part-1-bc2e1ae1b273">How to Build an Expandable List View in SwiftUI</a></blockquote><p>An accordion is a vertically stacked list of items where each item has a header (like a title) that, when tapped, expands to reveal more content (e.g., a description). Only one or multiple items can be expanded at a time, depending on the design. This pattern saves screen real estate and improves usability by hiding details until needed.</p><p>In our SFAccordionView, we’ll support multiple expansions (though you could easily modify it for single-expansion mode). It uses SwiftUI’s built-in animations for a polished feel, and includes scrolling behavior to ensure expanded content is visible.</p><h4>The Core Structures</h4><p>The code revolves around two main structs: SFAccordionItem for data and SFAccordionView for the UI. There’s also a helper view ContentCell for rendering each item.</p><h4>1. Defining the Data: SFAccordionItem</h4><p>This is a straightforward, recognizable struct used to hold the title and description for each accordion section.</p><pre>public struct SFAccordionItem: Identifiable, Hashable {<br>    private let uuid: UUID = UUID()<br>    public var id: UUID {<br>        return uuid<br>    }<br>    var title: String<br>    var description: String<br>    <br>    public init(title: String, description: String) {<br>        self.title = title<br>        self.description = description<br>    }<br>}</pre><ul><li><strong>Why UUID?</strong> We use a private UUID for the id to ensure uniqueness, making it compatible with SwiftUI’s ForEach and Identifiable protocol.</li><li><strong>Hashable conformance:</strong> This allows us to use the item in a Set for tracking selected (expanded) states.</li></ul><p>You can create an array of these items like so:</p><pre>let items = [<br>    SFAccordionItem(title: &quot;Section 1&quot;, description: &quot;This is a detailed explanation...&quot;),<br>    SFAccordionItem(title: &quot;Section 2&quot;, description: &quot;More details here...&quot;)<br>]</pre><h4>2. The Main View: SFAccordionView</h4><p>This is where the magic happens. It’s a View that takes an array of SFAccordionItem and renders them in a scrollable list.</p><pre>public struct SFAccordionView: View {<br>    @State private var listData: [SFAccordionItem]<br>    @State private var selectedcell: Set&lt;SFAccordionItem&gt; = []<br>    @State private var expandedIndex: Int? = nil // Track the index of the expanded item<br>    <br>    public init(listData: [SFAccordionItem] = []) {<br>        self.listData = listData<br>    }<br>    <br>    public var body: some View {<br>        ScrollViewReader { scrollProxy in<br>            ScrollView(.vertical, showsIndicators: false) {<br>                ForEach(listData.indices, id: \.self) { index in<br>                    let item = listData[index]<br>                    <br>                    ContentCell(item: item, expandable: selectedcell.contains(item))<br>                        .listRowSeparator(.hidden)<br>                        .modifier(ScrollCell())<br>                        .onTapGesture {<br>                            withAnimation(.easeInOut(duration: 0.35)) {<br>                                if selectedcell.contains(item) {<br>                                    selectedcell.remove(item)<br>                                } else {<br>                                    selectedcell.insert(item)<br>                                }<br>                            }<br>                            // Scroll to the expanded cell<br>                            if selectedcell.contains(item) {<br>                                expandedIndex = index<br>                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {<br>                                    scrollProxy.scrollTo(expandedIndex, anchor: .top)<br>                                }<br>                            }<br>                        }<br>                        .animation(.easeIn(duration: selectedcell.contains(item) ? 0.5 : 0.3), value: selectedcell.contains(item))<br>                        .padding(.vertical, 2)<br>                        .id(index)<br>                }<br>            }<br>            .listStyle(.plain)<br>            .onDisappear {<br>                expandedIndex = nil<br>                selectedcell = []<br>            }<br>        }<br>    }<br>}</pre><h3>Key Breakdown:</h3><h4><strong>@State Variables:</strong></h4><ul><li>listData: Holds the array of items (passed via init).</li><li>selectedcell: A Set to track which items are expanded. Using a Set ensures efficient insertion/removal and uniqueness.</li><li>expandedIndex: Tracks the last expanded item’s index for scrolling.</li></ul><h4><strong>ScrollViewReader and ScrollView:</strong></h4><ul><li>ScrollViewReader allows programmatic scrolling via scrollProxy.</li><li>ScrollView makes the list scrollable, hiding indicators for a cleaner look.</li><li>ForEach iterates over indices (not items) because we need the index for scrolling and IDs.</li></ul><h4><strong>Tap Gesture and Animations:</strong></h4><ul><li>On tap, we toggle the item’s presence in <strong><em>selectedcell</em></strong> with a smooth .<strong><em>easeInOut</em></strong> animation.</li><li>If expanding, we set expandedIndex and use DispatchQueue to scroll to the top of the cell after the animation completes (0.35 seconds delay, also defined as per your requirement).</li><li>Additionally, .<strong><em>animation</em></strong> modifiers handle expansion/collapse timing, making the UI feel responsive.</li></ul><h4><strong>.onDisappear:</strong></h4><ul><li>Resets state when the view disappears, preventing stale data in navigation flows.</li></ul><h4><strong>Modifiers:</strong></h4><ul><li>.listRowSeparator(.hidden) and .listStyle(.plain) give it a custom list appearance.</li><li>.id(index) assigns an ID for scrolling.</li><li>ScrollCell is a placeholder modifier (empty in the code); you could extend it for custom scrolling behavior.</li></ul><p>This setup allows multiple items to be expanded simultaneously. For single-expansion, clear the <strong><em>selectedcell</em></strong> before inserting a new item.</p><h4>3. Rendering Each Item: ContentCell</h4><p>This subview handles the visual representation of a single accordion item.</p><pre>struct ContentCell: View {<br>    private let item: SFAccordionItem<br>    private var expandable: Bool<br>    private let showDivider: Bool<br>    let width = UIScreen.main.bounds.width - 40<br>    private let dividerPadding = EdgeInsets(top: 5, leading: 0, bottom: 0, trailing: 0)<br>    <br>    var textColor: Color {<br>        .fromFDS(.textHeadline) // Assuming a custom design system color<br>    }<br>    var calculatedHeight: CGFloat = 0.0<br>    let plusIcon: Image = Image.icon(.plus) // Custom icon<br>    <br>    init(item: SFAccordionItem, expandable: Bool, showDivider: Bool = true) {<br>        self.calculatedHeight = heightForText(item.description, fontStyle: .body03, width: width)<br>        self.item = item<br>        self.expandable = expandable<br>        self.showDivider = showDivider<br>    }<br>    <br>    var body: some View {<br>        HStack(alignment: .top) {<br>            VStack(alignment: .leading) {<br>                if showDivider {<br>                    SFDivider() // Custom divider component<br>                        .padding(dividerPadding)<br>                }<br>                HStack {<br>                    Text(item.title)<br>                    Spacer()<br>                    plusIcon<br>                        .resizable()<br>                        .frame(width: 24, height: 24)<br>                        .imageScale(.medium)<br>                        .rotationEffect(.degrees(expandable ? 45 : 0))<br>                        .animation(.easeInOut(duration: 0.4), value: expandable)<br>                }<br>                .padding([.horizontal, .top], SpacingToken.spacing05.style.value) // Custom spacing<br>                .padding(.bottom, expandable ? SpacingToken.spacing03.style.value : SpacingToken.spacing05.style.value)<br>                .animation(.easeInOut(duration: 1), value: expandable)<br>                <br>                if expandable {<br>                    VStack(alignment: .leading) {<br>                        Text(item.description)<br>                            .foregroundColor(.gray)<br>                            .multilineTextAlignment(.leading)<br>                            .lineLimit(nil)<br>                            .transition(.opacity)<br>                            .frame(height: calculatedHeight, alignment: .topLeading)<br>                    }<br>                    .padding([.horizontal], SpacingToken.spacing05.style.value)<br>                    .animation(.smooth(duration: expandable ? 0.4 : 0.4), value: expandable)<br>                    .transition(.asymmetric(<br>                        insertion: .opacity,<br>                        removal: .opacity<br>                    ))<br>                }<br>            }<br>            .animation(.easeInOut(duration: expandable ? 0.5 : 0.2), value: expandable)<br>            Spacer()<br>        }<br>        .contentShape(Rectangle())<br>    }<br>}</pre><h4>Highlights:</h4><ul><li><strong>Initialization:</strong> Calculates calculatedHeight using a helper function (more on that below) to dynamically size the description frame.</li><li><strong>Layout:</strong> An HStack with a VStack for vertical stacking of divider, title row, and description.</li><li><strong>Title Row:</strong> Title text with custom styling, a spacer, and a plus icon that rotates 45 degrees on expansion (becoming a “minus” visually).</li><li><strong>Expandable Content:</strong> Shown only if expandable is true. Uses TypeWriterAnimation (assuming a custom view for typewriter effect) with opacity transitions for fade-in/out.</li><li><strong>Animations and Transitions:</strong> Multiple .animation and .transition modifiers ensure buttery-smooth expansions. The asymmetric transition handles insertion/removal gracefully.</li><li><strong>Custom Elements:</strong> Things like .fromFDS, SFDivider, SpacingToken, .applyTextStyle, and FontStyle appear to be from a design system (e.g., a company’s UI kit). In your app, replace these with standard SwiftUI equivalents like Color.primary, Divider(), or hardcoded paddings.</li></ul><p>The .contentShape(Rectangle()) makes the entire cell tappable.</p><h4>4. Dynamic Height Calculation: heightForText</h4><p>To avoid clipping or unnecessary scrolling in the description, we pre-calculate its height:</p><pre>func heightForText(_ text: String, width: CGFloat) -&gt; CGFloat {<br>    let font = UIFont.systemFont(ofSize: 14)<br>    let paragraphStyle = NSMutableParagraphStyle()<br>    paragraphStyle.lineHeightMultiple = 1<br>    let attributes: [NSAttributedString.Key: Any] = [<br>        .font: font,<br>        .paragraphStyle: paragraphStyle<br>    ]<br>    let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)<br>    let boundingBox = NSString(string: text).boundingRect(<br>        with: constraintRect,<br>        options: [.usesLineFragmentOrigin, .usesFontLeading],<br>        attributes: attributes,<br>        context: nil<br>    )<br>    return ceil(boundingBox.height)<br>}</pre><ul><li>This uses UIKit’s boundingRect for precise height based on text, font, and width.</li><li>Why UIKit? SwiftUI doesn’t have a built-in way to calculate text height dynamically, so bridging to UIFont and NSAttributedString is common.</li><li>Tip: Wrap this in a GeometryReader if you need runtime width adjustments, but here we hardcode UIScreen.main.bounds.width — 40 for padding.</li></ul><h3>Using SFAccordionView in Your App</h3><p>Simply instantiate it in your parent view:</p><pre>struct MyView: View {<br>    var body: some View {<br>        SFAccordionView(listData: [<br>            SFAccordionItem(title: &quot;FAQ 1&quot;, description: &quot;Answer...&quot;),<br>            // More items...<br>        ])<br>    }<br>}</pre><ul><li>Customize: Add borders, change icons, or limit to single expansion by modifying the tap gesture.</li><li>Performance: For long lists, this is efficient since SwiftUI lazily renders views.</li></ul><h4>Tips for SwiftUI Developers</h4><ul><li><strong>Animations Best Practices:</strong> Always use withAnimation for state changes and specific .<strong><em>animation</em></strong> modifiers for values. Test on devices for timing tweaks.</li><li><strong>Accessibility:</strong> Add <strong><em>.accessibilityLabel</em></strong> to the title and description for VoiceOver support.</li><li><strong>Edge Cases:</strong> Handle empty listData, very long descriptions (add clipping if needed), or dark mode compatibility.</li><li><strong>Extensions:</strong> Replace custom components with vanilla SwiftUI for portability. For example, use Image(systemName: “plus”) instead of Image.icon(.plus).</li><li><strong>Debugging:</strong> If animations stutter, reduce durations or use simpler curves like .linear.</li></ul><h3>Wrapping Up</h3><p>This SFAccordionView is a robust, animated component that showcases SwiftUI’s power for custom UIs. By understanding the state management, gestures, and height calculations, you can adapt it for your needs — perhaps adding images, buttons, or even nested accordions.</p><p>If you build on this, share your variations in the comments! For more SwiftUI tutorials, follow me on Medium. Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cf815ff09f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Enums: Advanced]]></title>
            <link>https://medium.com/@ankit9deshwal9/swift-enums-advanced-8df631e4ae9e?source=rss-718e92a470bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8df631e4ae9e</guid>
            <dc:creator><![CDATA[Ankit Kumar]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 13:14:26 GMT</pubDate>
            <atom:updated>2025-08-25T13:17:07.076Z</atom:updated>
            <content:encoded><![CDATA[<p>Associated Values, Pattern Matching and Diffrent Usecase’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7aKqem7zxTqlbmBA5cV8g.png" /></figure><p>Swift enums have evolved into one of the most <strong>powerful, expressive, and versatile</strong> features of the language. In 2025, they go far beyond simple switches and states — they’re essential for <strong>robust app architecture</strong>, <strong>SwiftUI</strong>, and <strong>async workflows</strong>.</p><p>This post dives into the <strong>advanced capabilities of enums</strong> — including associated values, pattern matching, and clean usage patterns that you should be using today.</p><h4><strong>1. Associated Values: Enums That Carry Data</strong></h4><p>Enums can store custom data per case, allowing you to model <strong>state + context</strong> together — especially useful for representing UI states, API responses, or app flows.</p><pre>enum AuthState {<br>    case idle<br>    case loading<br>    case success(user: User)<br>    case failure(errorMessage: String)<br>}</pre><p>Example Use: SwiftUI ViewModel</p><pre>switch authState {<br>case .success(let user):<br>    Text(&quot;Welcome, \(user.name)!&quot;)<br>case .failure(let message):<br>    Text(&quot;Oops: \(message)&quot;)<br>default:<br>    ProgressView()<br>}</pre><h4><strong>2. Pattern Matching: Write Safer, Smarter Code</strong></h4><p>Swift’s pattern matching lets you <strong>unwrap and handle values</strong> directly. It’s not just limited to switch — you can match patterns anywhere.</p><p>if case Example:</p><pre>if case .failure(let errorMessage) = authState {<br>    showError(message: errorMessage)<br>}</pre><p>guard case Example:</p><pre>guard case .success(let user) = authState else {<br>    return<br>}<br>print(&quot;Logged in as \(user.name)&quot;)</pre><p>No more messy if let chains — this reads like natural language.</p><h4><strong>3. Enums with Computed Properties: Encapsulate Logic</strong></h4><p>Enums can include computed properties for <strong>reusability and clarity</strong>.</p><pre>enum Subscription {<br>    case free<br>    case premium(expiry: Date)<br><br>    var isActive: Bool {<br>        switch self {<br>        case .free: return false<br>        case .premium(let expiry): return expiry &gt; Date()<br>        }<br>    }<br>}<br><br>let plan: Subscription = .premium(expiry: Date().addingTimeInterval(3600))<br>print(plan.isActive) // true</pre><h4><strong>4. Enums with Protocols: Add Behavior</strong></h4><p>By conforming enums to protocols, you unlock <strong>polymorphism and modularity</strong>.</p><pre>protocol MediaRenderable {<br>    var thumbnailURL: URL { get }<br>}<br><br>enum MediaType: MediaRenderable {<br>    case image(URL)<br>    case video(URL)<br><br>    var thumbnailURL: URL {<br>        switch self {<br>        case .image(let url), .video(let url):<br>            return url<br>        }<br>    }<br>}</pre><h4><strong>5. Enums in SwiftUI Navigation &amp; Routing</strong></h4><p>In SwiftUI 3.0+, enums are an <strong>elegant solution for navigation</strong> — type-safe, clean, and scalable.</p><pre>enum AppRoute: Hashable {<br>    case dashboard<br>    case profile(userID: String)<br>    case settings<br>}<br><br>@State private var path: [AppRoute] = []<br><br>NavigationStack(path: $path) {<br>    DashboardView()<br>        .navigationDestination(for: AppRoute.self) { route in<br>            switch route {<br>            case .dashboard: DashboardView()<br>            case .profile(let id): ProfileView(userID: id)<br>            case .settings: SettingsView()<br>            }<br>        }<br>}</pre><h4>6. Advanced Tricks You Should Be Using</h4><p>@dynamicMemberLookup with Enums</p><p>Access associated values directly:</p><pre>@dynamicMemberLookup<br>enum Result&lt;T&gt; {<br>    case success(T)<br>    case failure(Error)<br><br>    subscript&lt;U&gt;(dynamicMember keyPath: KeyPath&lt;T, U&gt;) -&gt; U? {<br>        switch self {<br>        case .success(let value): return value[keyPath: keyPath]<br>        default: return nil<br>        }<br>    }<br>}<br><br>let result: Result&lt;User&gt; = .success(User(name: &quot;John&quot;))<br>print(result.name) // Optional(&quot;John&quot;)</pre><h4>Conform Enums to Identifiable</h4><p>Great for SwiftUI lists or item-based views:</p><pre>enum ListItem: Identifiable {<br>    case person(id: UUID, name: String)<br>    case company(id: UUID, title: String)<br><br>    var id: UUID {<br>        switch self {<br>        case .person(let id, _), .company(let id, _): return id<br>        }<br>    }<br>}</pre><h4>Conclusion:</h4><p>In 2025, Swift enums are more than simple case lists — they’re a <strong>foundational tool</strong> for writing clean, modular, testable code.</p><blockquote>Whether you’re building complex state machines in SwiftUI or modeling domain logic in your app layer, mastering these enum techniques will make you a <strong>stronger, faster, and more reliable iOS developer</strong>.<br>Enjoyed this post? <br>Leave a comment with your favorite enum use case — or a trick I missed.<br>“I greatly value your feedback. Please share your thoughts or suggestions below.”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8df631e4ae9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build an Expandable List View in SwiftUI (with States) Part 1]]></title>
            <link>https://medium.com/@ankit9deshwal9/how-to-build-an-expandable-list-view-in-swiftui-with-states-part-1-bc2e1ae1b273?source=rss-718e92a470bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc2e1ae1b273</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui-5]]></category>
            <category><![CDATA[reusable-component]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Ankit Kumar]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 17:02:48 GMT</pubDate>
            <atom:updated>2025-06-30T09:44:40.006Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7aKqem7zxTqlbmBA5cV8g.png" /></figure><p>In many apps, especially ones with dynamic content or nested data, you often need a UI component that expands to reveal additional content. Think FAQ sections, product details, or grouped lists. In this tutorial, we’ll walk through building a <strong>fully functional Expandable List View</strong> in <strong>SwiftUI</strong> with:</p><ul><li>Create an expandable list view</li><li>Show a loading indicator during async operations</li><li>Display content or errors based on the load state</li><li>Add animation, icons, and interaction</li></ul><p>Let’s dive right in.</p><blockquote><strong>Define Your Loader State<br></strong>We start by defining a reusable enum to represent the <strong>loading state</strong> of our data. This helps separate concerns and avoids scattering async logic throughout the UI.</blockquote><pre>enum LoaderState&lt;T&gt; {<br>    case inProgress<br>    case success(T)<br>    case error(Error)<br>}</pre><p><strong>Explanation</strong>:<br>• T is a generic type, <strong>meaning </strong>it can represent any data type.<br>• This enum <strong>indicates</strong> whether:<br> <strong><em>- </em></strong><em>Data is loading (in progress)<br> </em><strong><em>- </em></strong><em>Data was loaded successfully (success)<br> </em><strong><em>- </em></strong><em>There was an error loading data (error)</em></p><p><strong>The ViewModel</strong><br>This will hold our loading logic and manage the data that powers the view.</p><pre>class ExpandableListVM: ObservableObject{<br>    @Published var loader: LoaderState&lt;String&gt; = .inProgress<br><br>    init() {<br>        // Simulate async data load<br>        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {<br>            self.loader = .success(&quot;Here is the content you loaded!&quot;)<br>        }<br>    }<br>}<br></pre><p><strong><em>Explanation</em></strong>:<br>• The ViewModel uses @Published to notify the viewer when the loader state changes.<br>• We’re simulating an async operation with DispatchQueue.main.asyncAfter</p><p><em>Note: You could replace this with real API calls or database queries.</em></p><p><strong>Create the ExpandCollapseView<br></strong>This is the <strong>core component</strong> — a reusable SwiftUI view that expands to show content once the loading is complete.</p><pre>struct ExpandCollapseView&lt;T, Content&gt;: View where Content: View {<br>    @Binding var expanded: Bool<br>    let title: String<br>    @Binding var loader: LoaderState&lt;T&gt;<br>    let content: (_ item: T) -&gt; Content<br><br>    var body: some View {<br>        VStack(alignment: .leading) {<br>            Button(action: {<br>                withAnimation {<br>                    expanded.toggle()<br>                }<br>            }) {<br>                HStack {<br>                    Text(title)<br>                    Spacer()<br>                    Image(systemName: expanded ? &quot;minus&quot; : &quot;plus&quot;)<br>                }<br>            }<br><br>            if expanded {<br>                switch loader {<br>                case .inProgress:<br>                    ProgressView()<br>                case .success(let item):<br>                    content(item)<br>                case .error(let error):<br>                    Text(&quot;Error: \(error.localizedDescription)&quot;)<br>                        .foregroundColor(.red)<br>                }<br>            }<br>        }<br>        .padding()<br>        .background(.black)<br>        .cornerRadius(8)<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>expandedDetermines whether the view is expanded or collapsed.</li><li>loader Indicates the loading state.</li><li>content A closure that returns the content view once loading succeeds.</li><li>Toggling expanded is animated for smoothness.</li><li>We conditionally show content based on the loader state.</li></ul><p><strong>Use ExpandCollapseView in a List<br></strong>We’ll now use our component in a parent view that uses SwiftUI’s NavigationView and List.</p><pre>struct ExpandableListView: View {<br>    @ObservedObject var vm = ExpandableListVM()<br>    @State private var isExpanded: Bool = false<br><br>    var body: some View {<br>        NavigationView {<br>            List {<br>                ExpandCollapseView(<br>                    expanded: $isExpanded,<br>                    title: &quot;Expandable Section&quot;,<br>                    loader: $vm.loader<br>                ) { item in<br>                    Text(item)<br>                        .padding()<br>                        .background(.green)<br>                        .cornerRadius(5)<br>                }<br>            }<br>            .listStyle(.inset)<br>            .navigationTitle(&quot;Expandable List&quot;)<br>        }<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><blockquote>@ObservedObject connects our view to the ViewModel, so it listens for changes.</blockquote><blockquote>ExpandCollapseView is embedded in a SwiftUI List.</blockquote><ul><li>We use @State to track whether the section is expanded.</li></ul><h4>Optional: Add Subtitles, Icons, and Custom Actions</h4><p>Want to customize your component with a subtitle, icon, or a custom tap handler? ExpandCollapseView can be extended like this:</p><pre>init(<br>    expanded: Binding&lt;Bool&gt;,<br>    title: String,<br>    subTitle: String? = nil,<br>    icon: String? = nil,<br>    action: (() -&gt; Void)? = nil,<br>    scroll: Bool = true,<br>    bgColor: Color = .black,<br>    loader: Binding&lt;LoaderState&lt;T&gt;&gt;,<br>    @ViewBuilder content: @escaping (_ item: T) -&gt; Content<br>)</pre><p>Then update the header button:</p><pre>HStack {<br>    VStack(alignment: .leading) {<br>        Text(title).bold()<br>        if let subTitle = subTitle {<br>            Text(subTitle).font(.subheadline).foregroundColor(.secondary)<br>        }<br>    }<br><br>    Spacer()<br><br>    if let icon = icon {<br>        Image(systemName: icon)<br>            .frame(width: 20, height: 20)<br>    }<br><br>    Image(systemName: expanded ? &quot;chevron.up&quot; : &quot;chevron.down&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*xkSYDoHpORpzRvfjOiuioQ.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F783j3HK0xyg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2F783j3HK0xyg%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F783j3HK0xyg%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3b8003006ad9afdcc885a3d412e972c/href">https://medium.com/media/a3b8003006ad9afdcc885a3d412e972c/href</a></iframe><h3>Final Output</h3><p>When everything is wired up:</p><ul><li>You tap on the header, it animates open.</li><li>It shows a loading spinner.</li><li>After 2 seconds, it shows your content.</li><li>You can collapse/expand it at will.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc2e1ae1b273" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>