<?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 Adam Dev on Medium]]></title>
        <description><![CDATA[Stories by Adam Dev on Medium]]></description>
        <link>https://medium.com/@iamCoder?source=rss-1cde0ddee7b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ij3Rk03PEW1bay8yPJenMQ.jpeg</url>
            <title>Stories by Adam Dev on Medium</title>
            <link>https://medium.com/@iamCoder?source=rss-1cde0ddee7b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:59:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamCoder/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[Bringing UIKit into SwiftUI: A Practical Example with ActivityIndicator]]></title>
            <link>https://medium.com/@iamCoder/bringing-uikit-into-swiftui-a-practical-example-with-activityindicator-2e2244a77220?source=rss-1cde0ddee7b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e2244a77220</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Adam Dev]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 11:17:56 GMT</pubDate>
            <atom:updated>2026-01-25T11:17:56.654Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dlwhPTFNyrSdMCSeCEDHtQ.png" /></figure><p>SwiftUI is a powerful framework for building modern, declarative UIs on Apple platforms. But sometimes, we still need to leverage <strong>UIKit components</strong> that don’t yet have a native SwiftUI equivalent. A common example is the classic <strong>UIActivityIndicatorView</strong>, the spinning loader.</p><p>In this article, we’ll explore how to <strong>wrap UIKit views for use in SwiftUI</strong> and make them fully reactive with SwiftUI’s state system.</p><h3>1. Why Wrap UIKit Views?</h3><p>SwiftUI is growing rapidly, but not every UIKit component has a SwiftUI counterpart. Some use cases, like advanced pickers, spinners, or specialized controls, may require:</p><ul><li>Access to UIKit-only APIs</li><li>Legacy components that already work in your project</li><li>Fine-grained control over behavior</li></ul><p>SwiftUI provides UIViewRepresentable for this exact purpose: it allows us to embed UIKit views seamlessly. It also provides 2 default methods for this purpose namely : <a href="https://developer.apple.com/documentation/swiftui/uiviewrepresentable/makeuiview(context:)">makeUIView(context:) </a>&amp; <a href="https://developer.apple.com/documentation/swiftui/uiviewrepresentable/updateuiview(_:context:)">updateUIView(_:context:)</a></p><h3>2. Creating a SwiftUI-Compatible Activity Indicator</h3><p>Here’s the implementation:</p><pre>import SwiftUI<br><br>struct ActivityIndicator: UIViewRepresentable {<br>    <br>    let animating: Bool<br>    <br>    func makeUIView(context: Context) -&gt; UIActivityIndicatorView {<br>        UIActivityIndicatorView()<br>    }<br>    <br>    func updateUIView(_ uiView: UIActivityIndicatorView, context: Context) {<br>        if animating {<br>            uiView.startAnimating()<br>        } else {<br>            uiView.stopAnimating()<br>        }<br>    }<br>}</pre><h3>Key Points:</h3><ol><li><strong>Conform to </strong><a href="https://developer.apple.com/documentation/swiftui/uiviewrepresentable"><strong>UIViewRepresentable</strong></a><br> This protocol lets SwiftUI manage a UIKit UIView.</li><li><a href="https://developer.apple.com/documentation/swiftui/uiviewrepresentable/makeuiview(context:)"><strong>makeUIView(context:)</strong></a><strong> </strong><br> Creates the UIActivityIndicatorView instance. Think of it as “instantiate the UIKit view.” This function is by default provided by the apple.</li><li><a href="https://developer.apple.com/documentation/swiftui/uiviewrepresentable/updateuiview(_:context:)"><strong>updateUIView(_:context:)</strong></a><br> Called whenever SwiftUI updates the view. Here we react to the animating state and start or stop the spinner accordingly. This function is by default provided by the apple.</li></ol><h3>3. Using the Activity Indicator in SwiftUI</h3><p>Next, we integrate it into a SwiftUI view with live state updates:</p><pre>struct UIKitIntoSwiftUISample: View {<br>    @State private var isAnimating: Bool = true<br>    <br>    var body: some View {<br>        VStack {<br>            ActivityIndicator(animating: isAnimating)<br>            <br>            HStack {<br>                Text(&quot;Toggle to Stop&quot;)<br>                    .font(.title)<br>                    .lineLimit(2)<br>                    .padding()<br>                <br>                Toggle(isOn: $isAnimating) {<br>                    Text(&quot;&quot;)<br>                }<br>            }<br>            .padding()<br>        }<br>    }<br>}</pre><h3>How it Works:</h3><ul><li>@State private var isAnimating keeps track of whether the spinner should animate.</li><li>The Toggle updates isAnimating, which triggers SwiftUI to call updateUIView on ActivityIndicator.</li><li>The spinner reacts instantly — fully integrated with SwiftUI’s reactive model.</li></ul><h3>4. Why This Approach is Powerful</h3><ul><li><strong>Reactive:</strong> Changes to @State automatically update the UIKit view.</li><li><strong>Reusable:</strong> Wrap any UIKit component in a UIViewRepresentable to make it SwiftUI-compatible.</li><li><strong>Minimal boilerplate:</strong> Just two methods — makeUIView and updateUIView.</li></ul><h3>5. Next Steps</h3><p>This pattern is useful beyond activity indicators:</p><ul><li>Embedding custom UIKit controls (e.g., sliders, pickers, or maps)</li><li>Integrating legacy UIKit views into a modern SwiftUI app</li><li>Wrapping third-party UIKit components</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e2244a77220" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring SF Symbols in SwiftUI: A Practical Walkthrough]]></title>
            <link>https://medium.com/@iamCoder/exploring-sf-symbols-in-swiftui-a-practical-walkthrough-6d6d9e7ece38?source=rss-1cde0ddee7b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d6d9e7ece38</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Adam Dev]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 10:38:54 GMT</pubDate>
            <atom:updated>2026-01-25T10:38:54.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kiSY5AQ7RoswTABwmSSYWw.png" /></figure><p>SF Symbols are one of SwiftUI’s quiet superpowers. With just a few modifiers, you can animate, color, scale, and adapt icons to match system behavior — all while staying accessible and testable.</p><p>In this article, we’ll walk through a small SwiftUI sample that demonstrates <strong>symbol variants, rendering modes, effects, accessibility identifiers, and dynamic state-driven icons</strong>.</p><p>Let’s break it down piece by piece.</p><h3>The View Setup</h3><pre>struct SFSymbolsSample: View {<br>    @State var wifiSelection: Int?</pre><p>We start with a simple View and a @State property:</p><ul><li>wifiSelection tracks the selected segment in a Picker</li><li>The UI reacts automatically when this value changes</li></ul><p>This is the foundation of SwiftUI’s declarative approach.</p><h3>1. Using Symbol Variants with Multiple Images</h3><pre>HStack(spacing: 24) {<br>    Image(systemName: &quot;c&quot;)<br>    Image(systemName: &quot;o&quot;)<br>    Image(systemName: &quot;o&quot;)<br>    Image(systemName: &quot;k&quot;)<br>}<br>.symbolVariant(.fill.circle)<br>.foregroundStyle(.yellow, .purple)<br>.font(.title)</pre><h3>What’s happening here?</h3><ul><li>Each letter is an SF Symbol</li><li>.symbolVariant(.fill.circle) transforms all of them into <strong>filled circular variants</strong></li><li>.foregroundStyle(.yellow, .purple) applies <strong>primary and secondary colors</strong></li><li>Modifiers are applied once to the entire HStack</li></ul><p>💡 <strong>Key takeaway:</strong><br> Symbol variants let you change an icon’s appearance without changing the symbol name.</p><h3>2. Multicolor Symbols</h3><pre>HStack {<br>   Image(systemName: &quot;allergens&quot;)<br>   Image(systemName: &quot;ladybug&quot;)<br>}<br>.symbolVariant(.fill)<br>.symbolRenderingMode(.multicolor)<br>.font(.largeTitle)</pre><p>Here we enable <strong>multicolor rendering</strong>, allowing SF Symbols to display their built-in color palettes.</p><ul><li>.symbolRenderingMode(.multicolor) overrides single-color styling</li><li>Works only for symbols designed with multiple layers</li></ul><p>This is ideal for system-like visuals that feel native and expressive.</p><h3>3. Individual Styling and Accessibility</h3><pre>HStack {<br>    Image(systemName: &quot;b.circle.fill&quot;)<br>    Image(systemName: &quot;o.circle.fill&quot;)<br>        .foregroundStyle(.red)<br>    Image(systemName: &quot;o.circle.fill&quot;)<br>        .imageScale(.large)<br>    Image(systemName: &quot;k.circle.fill&quot;)<br>        .accessibility(identifier: &quot;Letter K&quot;)<br>}</pre><p>This section shows <strong>fine-grained control</strong>:</p><ul><li>Individual images can override shared styling</li><li>.imageScale(.large) changes symbol scale without affecting others</li><li>.accessibility(identifier:) adds a <strong>UI-test-only identifier</strong></li></ul><p>🧪 The accessibility identifier:</p><ul><li>Is invisible to users</li><li>Not read by VoiceOver</li><li>Used by UI tests to reliably find elements</li></ul><h3>4. Dynamic Icons with Picker + State</h3><pre>Picker(&quot;Pick One&quot;, selection: $wifiSelection) {<br>    Text(&quot;No Wifi&quot;).tag(0)<br>    Text(&quot;Searching&quot;).tag(1)<br>    Text(&quot;Wifi On&quot;).tag(2)<br>}<br>.pickerStyle(.segmented)</pre><p>The segmented picker updates wifiSelection. SwiftUI automatically re-renders the UI when this value changes.</p><p>This is where SwiftUI really shines.</p><h3>5. Conditional Views with Group</h3><pre>Group {<br>    switch wifiSelection {<br>    case 0:<br>        Image(systemName: &quot;wifi&quot;)<br>            .symbolVariant(.slash)<br>    case 1:<br>        Image(systemName: &quot;wifi&quot;)<br>            .symbolEffect(.variableColor.iterative.reversing)<br>    default:<br>        Image(systemName: &quot;wifi&quot;)<br>            .foregroundStyle(.blue)<br>    }<br>}<br>.foregroundStyle(.secondary)<br>.font(.title)</pre><h3>Why use Group?</h3><ul><li>Each switch case returns a different modified Image</li><li>SwiftUI requires all branches to resolve to <strong>one view type</strong></li><li>Group acts as a <strong>transparent container</strong></li><li>Shared modifiers are applied once, cleanly</li></ul><p>🎯 The result:</p><ul><li>No layout impact</li><li>No performance cost</li><li>Cleaner, more readable code</li></ul><h3>Symbol Effects in Action</h3><p>The .symbolEffect(.variableColor.iterative.reversing) modifier adds a subtle animated effect to the Wi-Fi icon, perfect for indicating a “searching” state.</p><p>These effects:</p><ul><li>Are system-optimized</li><li>Respect accessibility settings</li><li>Feel native out of the box</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d6d9e7ece38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom View Modifiers in SwiftUI (With Practical Examples)]]></title>
            <link>https://medium.com/@iamCoder/custom-view-modifiers-in-swiftui-with-practical-examples-6a53a101ae6a?source=rss-1cde0ddee7b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a53a101ae6a</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Adam Dev]]></dc:creator>
            <pubDate>Sun, 18 Jan 2026 05:49:10 GMT</pubDate>
            <atom:updated>2026-01-18T05:50:53.621Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S6cOERMMGG941sXSHA-VGQ.png" /></figure><p>When building SwiftUI apps, it’s very common to repeat the same styling code again and again:</p><pre>.font(.headline)<br>.foregroundColor(.white)<br>.padding()<br>.background(Color.blue)<br>.cornerRadius(10)</pre><p>At first this feels fine — but as your app grows, your body becomes cluttered, hard to read, and difficult to maintain.</p><p>This is exactly where <strong>custom view modifiers</strong> shine</p><p>In this article, we’ll cover:</p><ul><li>What a custom view modifier is</li><li>How to create one</li><li>How to use parameters</li><li>Best practices</li><li>When to use a modifier vs a custom view</li></ul><h3>What Is a Custom View Modifier?</h3><p>A <strong>custom view modifier</strong> is a reusable piece of UI logic that modifies an existing view.</p><p>In SwiftUI, modifiers:</p><ul><li>Do <strong>not</strong> create new views</li><li>Instead, they <strong>decorate</strong> existing views</li></ul><p>Technically, a custom modifier is a type that conforms to the <strong>ViewModifier</strong> protocol.</p><h3>Basic Custom View Modifier</h3><p>Let’s create a reusable <strong>Primary Button Style</strong>.</p><h3>Step 1: Create the modifier</h3><pre>struct PrimaryButtonModifier: ViewModifier {<br>    func body(content: Content) -&gt; some View {<br>        content<br>            .font(.headline)<br>            .foregroundColor(.white)<br>            .padding()<br>            .frame(maxWidth: .infinity)<br>            .background(Color.blue)<br>            .cornerRadius(10)<br>    }<br>}</pre><p>Here:</p><ul><li>content represents the view being modified</li><li>We apply styling on top of it</li></ul><h3>Step 2: Apply the modifier</h3><pre>Button(&quot;Login&quot;) {<br>    print(&quot;Tapped&quot;)<br>}<br>.modifier(PrimaryButtonModifier())</pre><p>This works — but SwiftUI encourages a cleaner syntax.</p><h3>Best Practice: View Extension for Clean Syntax</h3><p>Instead of writing .modifier(…) everywhere, add an extension:</p><pre>extension View {<br>    func primaryButtonStyle() -&gt; some View {<br>        self.modifier(PrimaryButtonModifier())<br>    }<br>}</pre><p>Now your code looks much cleaner:</p><pre>Button(&quot;Login&quot;) { }<br>    .primaryButtonStyle()</pre><p>This reads naturally and improves code readability.</p><h3>Custom View Modifier With Parameters</h3><p>Modifiers can accept parameters, making them flexible.</p><h3>Example: Card Style</h3><pre>struct CardModifier: ViewModifier {<br>    let backgroundColor: Color<br><br>    func body(content: Content) -&gt; some View {<br>        content<br>            .padding()<br>            .background(backgroundColor)<br>            .cornerRadius(12)<br>            .shadow(radius: 5)<br>    }<br>}</pre><p>Extension:</p><pre>extension View {<br>    func cardStyle(background: Color = .white) -&gt; some View {<br>        modifier(CardModifier(backgroundColor: background))<br>    }<br>}</pre><p>Usage:</p><pre>Text(&quot;Hello SwiftUI&quot;)<br>    .cardStyle(background: .gray.opacity(0.2))</pre><h3>Conditional Logic Inside a View Modifier</h3><p>You can add conditions inside a modifier — perfect for validation or error states.</p><h3>Example: Error Border</h3><pre>struct ErrorBorderModifier: ViewModifier {<br>    let showError: Bool<br><br>    func body(content: Content) -&gt; some View {<br>        content<br>            .overlay(<br>                RoundedRectangle(cornerRadius: 8)<br>                    .stroke(showError ? Color.red : Color.clear, lineWidth: 1)<br>            )<br>    }<br>}</pre><p>Usage:</p><pre>TextField(&quot;Username&quot;, text: $username)<br>    .modifier(ErrorBorderModifier(showError: isInvalid))</pre><p>This keeps validation logic reusable and consistent across the app.</p><h3>Real-World Example: Input Field Styling</h3><p>Here’s a practical modifier used in real apps:</p><pre>extension View {<br>    func inputFieldStyle(isFocused: Bool) -&gt; some View {<br>        self<br>            .padding()<br>            .background(Color.white)<br>            .overlay(<br>                RoundedRectangle(cornerRadius: 8)<br>                    .stroke(isFocused ? Color.blue : Color.gray, lineWidth: 1)<br>            )<br>    }<br>}</pre><p>Usage with @FocusState:</p><pre>TextField(&quot;Email&quot;, text: $email)<br>    .inputFieldStyle(isFocused: focusedField == .email)</pre><h3>Rule of Thumb</h3><ul><li><strong>Styling &amp; decoration → ViewModifier</strong></li><li><strong>Layout &amp; composition → Custom View</strong></li></ul><h3>Why You Should Use Custom View Modifiers</h3><p>✅ Cleaner body code</p><p>✅ Centralized UI updates</p><p>✅ Easy reusability</p><p>✅ Better SwiftUI composition</p><p>✅ Scales well for large apps</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a53a101ae6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ iOS 26 Introduces the Liquid Tab Bar]]></title>
            <link>https://medium.com/@iamCoder/ios-26-introduces-the-liquid-tab-bar-5c9d7aeac8b7?source=rss-1cde0ddee7b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c9d7aeac8b7</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Adam Dev]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 17:08:41 GMT</pubDate>
            <atom:updated>2025-12-11T17:08:41.849Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A new era of fluid navigation in SwiftUI</em></p><p>Apple’s iOS 26 release brings a major UI update: the <strong>Liquid Tab Bar</strong>. It’s flexible, animated, and context-aware — finally making navigation feel dynamic instead of static. Tabs now react with fluid motion, stretch when selected, and adapt based on what the user is doing.</p><h3>💡 Why the Liquid Tab Bar Matters</h3><p>Apple’s goal is simple: make navigation <strong>responsive and emotionally intelligent</strong>. The new tab bar:</p><ul><li>Moves and reshapes with fluid physics</li><li>Adapts to content and gestures</li><li>Works seamlessly with bottom accessories</li><li>Creates a more immersive, modern UI experience</li></ul><p>It’s a small change with big impact across app design.</p><h3>🔍 The New Search Behavior (Important!)</h3><p>One of the most interesting improvements is how <strong>search</strong> integrates with tabs.</p><p>✔️ <strong>You must select </strong><strong>.search to separate the search interface from the rest of the bar.</strong><br>✔️ Adding <strong>.searchable</strong> to the TabView and placing a NavigationStack inside the search tab makes the tab bar <strong>disappear and get replaced by a search bar</strong>, just like in Apple News.</p><p>This gives users a focused, full-width search mode without any extra logic.</p><h3>🧪 Quick Example</h3><pre><br>import SwiftUI<br><br>struct ContentView: View {<br>    var body: some View {<br>        TabView {<br>            <br>            Tab(&quot;Write&quot;, systemImage: &quot;pencil.tip.crop.circle.fill&quot;) {<br>                VStack {<br>                    Image(systemName: &quot;pencil.tip.crop.circle.fill&quot;)<br>                    Text(&quot;Write&quot;)<br>                }<br>                .frame(maxWidth: .infinity, maxHeight: .infinity)<br>                .background(Color.yellow)<br>                <br>            }<br>            <br>            Tab(&quot;Send&quot;, systemImage: &quot;paperplane.fill&quot;) {<br>                VStack {<br>                    Image(systemName: &quot;paperplane.fill&quot;)<br>                    <br>                    Text(&quot;Send&quot;)<br>                }<br>                .frame(maxWidth: .infinity, maxHeight: .infinity)<br>                .background(Color.mint)<br>            }<br>            <br>            Tab(&quot;Paste&quot;, systemImage: &quot;list.clipboard.fill&quot;) {<br>                VStack {<br>                    Image(systemName: &quot;list.clipboard.fill&quot;)<br>                    Text(&quot;Paste&quot;)<br>                }<br>                .frame(maxWidth: .infinity, maxHeight: .infinity)<br>                .background(Color.indigo)<br>            }<br>            <br>            Tab(&quot;Search&quot;, systemImage: &quot;magnifyingglass&quot;, role: .search) {<br>                NavigationStack {<br>                    VStack {<br>                        Image(systemName: &quot;magnifyingglass&quot;)<br>                        Text(&quot;Search&quot;)<br>                    }<br>                    .frame(maxWidth: .infinity, maxHeight: .infinity)<br>                    .background(Color.orange)<br>                }<br>            }<br>        }<br>        .searchable(text: .constant(&quot;&quot;), prompt: Text(&quot;Search&quot;))<br>        .tint(.pink)<br><br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*rSPeNU5NhKioC0zPEvIMWA.png" /><figcaption>Fluid TabBar iOS 26</figcaption></figure><p>The Liquid Tab Bar isn’t just a visual refresh — it changes how we think about bottom navigation. Fluid motion, smart search integration, and adaptive accessories make iOS apps feel more alive than ever.</p><p>If you’re designing for iOS 26, now’s the time to rethink your tab bar.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c9d7aeac8b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Size Classes in iOS: How to Show or Hide UI Elements in Portrait and Landscape]]></title>
            <link>https://medium.com/@iamCoder/mastering-size-classes-in-ios-how-to-show-or-hide-ui-elements-in-portrait-and-landscape-75bea8ba1256?source=rss-1cde0ddee7b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/75bea8ba1256</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[size-classes]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Adam Dev]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 01:53:55 GMT</pubDate>
            <atom:updated>2025-11-14T01:55:50.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rv7-fK9_hQFg-SXZpeuhBw.png" /></figure><p>Modern iOS apps must adapt gracefully to different screen sizes, orientations, and device categories. A layout that works beautifully in portrait may feel cramped or awkward in landscape. Apple’s Auto Layout and Size Classes make it possible to create flexible, responsive designs — but they can feel confusing at first.</p><p>In this article, we’ll decode size classes, understand how orientation changes affect them, and learn how to design UI elements that show in portrait but hide in landscape — all using Storyboard and Swift.</p><h3>📌 What Are Size Classes?</h3><p>iOS describes screen space using <strong>two simple traits</strong>:</p><ul><li><strong>Width size class</strong></li><li><strong>Height size class</strong></li></ul><p>Each of these traits can be either:</p><ul><li><strong>Compact</strong> → Small space</li><li><strong>Regular</strong> → Large space</li></ul><p>This system lets Apple maintain a common layout language across iPhones, iPads, multitasking modes, and even Mac Catalyst.</p><h3>✔️ Simplest definition:</h3><ul><li><strong>Compact = Small/hard to fit UI</strong></li><li><strong>Regular = Spacious/easy to fit UI</strong></li></ul><h3>📱 Size Classes for Common Devices</h3><h3>iPhone Portrait</h3><ul><li><strong>Width: Compact</strong></li><li><strong>Height: Regular</strong></li></ul><h3>iPhone Landscape</h3><p>Small iPhones:</p><ul><li><strong>Width: Compact</strong></li><li><strong>Height: Compact</strong></li></ul><p>Pro Max / Plus models:</p><ul><li><strong>Width: Regular</strong></li><li><strong>Height: Compact</strong></li></ul><h3>iPad (Portrait &amp; Landscape)</h3><ul><li><strong>Width: Regular</strong></li><li><strong>Height: Regular</strong></li></ul><p>This means an iPad always has lots of room, while an iPhone usually doesn’t — especially in landscape.</p><h3>🎯 Understanding Trait Changes</h3><p>When a user rotates the device or enters Split View, iOS updates the app’s <strong>trait collection</strong>. This includes:</p><ul><li>Size classes</li><li>Dark/Light mode</li><li>Dynamic type size</li></ul><p>iOS notifies your view controller through:</p><pre>override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)</pre><p>This method is your chance to adapt the UI.</p><h3>🎬 Practical Goal: Show a Button Only in Portrait Mode</h3><p>Many apps hide certain UI elements in landscape — for example, keeping the UI clean during video playback or simplifying forms.</p><p>We’ll explore two ways to implement this:</p><ol><li><strong>Using Storyboard only (recommended when possible)</strong></li><li><strong>Using Swift code (for more control, especially on iPad)</strong></li></ol><h3>🧩 Method 1: Show/Hide Using Size Classes in Storyboard</h3><p>This approach uses <strong>Installed Variations</strong>, telling iOS to include or exclude the button depending on the size class.</p><h3>🔧 Steps</h3><ol><li>Select the button in Storyboard.</li><li>Open the <strong>Attributes Inspector</strong>.</li><li>Find the <strong>“Installed”</strong> checkbox.</li><li>Click the <strong>+</strong> icon next to it (Add Variation).</li><li>Choose: <strong>Height = Regular</strong>.</li></ol><p>Why? On most iPhones:</p><ul><li><strong>Portrait → Height = Regular</strong> (button appears)</li><li><strong>Landscape → Height = Compact</strong> (button removed)</li></ul><p>This cleanly removes the button from the view hierarchy — no space reserved.</p><h3>⚠️ Important Note</h3><p>On <strong>iPads</strong>, height is always Regular — even in landscape.</p><p>That means the button will appear in:</p><ul><li>iPad Portrait ✔️</li><li>iPad Landscape ❌ (not hidden)</li></ul><p>If you want universal portrait-only behavior, use Method 2.</p><h3>🧩 Method 2: Using Swift to Hide the Button When Orientation Changes</h3><p>This method gives full control.</p><h3>Step 1: Create an IBOutlet</h3><pre>@IBOutlet weak var myButton: UIButton!</pre><h3>Step 2: Update the button on trait changes</h3><pre>override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {<br>    super.traitCollectionDidChange(previousTraitCollection)<br>    updateButtonVisibility(for: traitCollection)<br>}</pre><h3>Step 3: Define visibility rules</h3><pre>private func updateButtonVisibility(for traits: UITraitCollection) {<br>    let isLandscape = traits.verticalSizeClass == .compact<br>    myButton.isHidden = isLandscape<br>}</pre><h3>Why this works</h3><p>On iPhone:</p><ul><li>Portrait → <strong>verticalSizeClass = Regular</strong> → button visible</li><li>Landscape → <strong>verticalSizeClass = Compact</strong> → button hidden</li></ul><p>On iPad:</p><ul><li>verticalSizeClass stays Regular</li><li>Use geometry-based detection if needed:</li></ul><pre>let isLandscape = view.bounds.width &gt; view.bounds.height<br>myButton.isHidden = isLandscape</pre><h3>🎥 How traitCollectionDidChange Actually Works</h3><p>Think of it like a system message:</p><blockquote><em>“The environment changed — update your UI.”</em></blockquote><p>It triggers when:</p><ul><li>User rotates the device</li><li>App switches light/dark mode</li><li>iPad enters split view</li><li>Dynamic type size changes</li></ul><p>This is the heart of responsive UIKit design.</p><h3>🧭 Best Practices for Adaptive UI</h3><h3>✔️ Prefer Auto Layout first</h3><p>Most UI can adapt automatically.</p><h3>✔️ Use Size Classes for structural changes</h3><p>Examples:</p><ul><li>Stack views switching from vertical → horizontal</li><li>Replacing a tab bar with a sidebar</li></ul><h3>✔️ Use traitCollectionDidChange for behavioral changes</h3><p>Examples:</p><ul><li>Show/hide elements</li><li>Update constraints</li><li>Refresh data</li></ul><h3>✔️ Always test on multiple devices</h3><p>Different iPhones behave differently:</p><ul><li>Pro Max landscape → Regular width</li><li>Small iPhone landscape → Compact width</li></ul><h3>📌 Conclusion</h3><p>Size classes are the foundation of adaptive design in iOS. Understanding Compact vs Regular makes it possible to build layouts that feel natural regardless of orientation or device.</p><p>To show a button only in portrait:</p><ul><li>Use <strong>Installed Variations</strong> in Storyboard for simple iPhone-only layouts.</li><li>Use <strong>traitCollectionDidChange</strong> in Swift for full control across iPhone and iPad.</li></ul><p>With these tools, your UI becomes flexible, clean, and user‑friendly on every screen.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75bea8ba1256" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Dependency Injection in Swift: A Clean, Testable ViewModel Example (UIKit/SwiftUI + Unit Tests)]]></title>
            <link>https://medium.com/@iamCoder/dependency-injection-in-swift-a-clean-testable-viewmodel-example-uikit-swiftui-unit-tests-bb67b2c88fb9?source=rss-1cde0ddee7b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb67b2c88fb9</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Adam Dev]]></dc:creator>
            <pubDate>Tue, 21 Oct 2025 04:34:54 GMT</pubDate>
            <atom:updated>2025-11-08T03:14:40.897Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zs0kZzpmd9-GZo9OBlFnfA.png" /></figure><p>When building iOS apps, you’ve probably seen classes that <strong>create their own dependencies</strong> — like a ViewModel initializing its own APIManager.</p><p>That might <em>work</em>, but it quickly turns into <strong>tightly coupled</strong>, <strong>hard-to-test</strong> code.</p><p>That’s where <strong>Dependency Injection (DI)</strong> comes in — a simple but powerful design pattern that makes your code <strong>modular</strong>, <strong>testable</strong>, and <strong>clean</strong>.</p><h3>🧠 What Is Dependency Injection?</h3><p><strong>Dependency Injection</strong> means <em>giving</em> an object its dependencies instead of letting it <em>create them</em>.</p><p>In simple words:</p><blockquote><em>“Don’t make your ViewModel build its own APIManager — hand it one.”</em></blockquote><p>This small shift in design unlocks huge benefits:</p><ul><li>✅ Easier Unit Testing</li><li>✅ Loosely Coupled Code</li><li>✅ Cleaner Architecture</li><li>✅ Swappable Dependencies (e.g., real vs mock API)</li></ul><p>Let’s see how to apply DI step by step in a UIKit project.</p><h3>🧱 Step 1: Define the Product Model</h3><p>We’ll start with a simple model for our data:</p><pre>import Foundation<br><br>struct Product: Codable, Equatable {<br>    let id: Int<br>    let name: String<br>}</pre><h3>🔌 Step 2: Create a Protocol for the Dependency</h3><p>We’ll define a protocol that describes how to fetch products.<br> Our ViewModel will depend on this <strong>protocol</strong>, not a concrete class.</p><pre>protocol ProductService {<br>    func fetchProducts(completion: @escaping (Result&lt;[Product], Error&gt;) -&gt; Void)<br>}</pre><h3>🌐 Step 3: Real API Service (Production Dependency)</h3><p>Here’s a fake API manager that simulates fetching data from the network.</p><pre>final class APIManager: ProductService {<br>    func fetchProducts(completion: @escaping (Result&lt;[Product], Error&gt;) -&gt; Void) {<br>        DispatchQueue.global().asyncAfter(deadline: .now() + 1) {<br>            let products = [<br>                Product(id: 1, name: &quot;iPhone&quot;),<br>                Product(id: 2, name: &quot;MacBook&quot;),<br>                Product(id: 3, name: &quot;iPad&quot;)<br>            ]<br>            completion(.success(products))<br>        }<br>    }<br>}</pre><h3>🧪 Step 4: Mock Service for Testing</h3><p>Mocks are essential when you don’t want to hit the network during unit tests.</p><pre>final class MockProductService: ProductService {<br>    var shouldReturnError = false<br>    <br>    func fetchProducts(completion: @escaping (Result&lt;[Product], Error&gt;) -&gt; Void) {<br>        if shouldReturnError {<br>            completion(.failure(NSError(domain: &quot;MockError&quot;, code: -1)))<br>        } else {<br>            let mockProducts = [<br>                Product(id: 101, name: &quot;Mock Phone&quot;),<br>                Product(id: 102, name: &quot;Mock Laptop&quot;)<br>            ]<br>            completion(.success(mockProducts))<br>        }<br>    }<br>}</pre><h3>🧠 Step 5: The ViewModel — with Dependency Injection</h3><p>Now the magic happens.<br> We inject a ProductService dependency instead of creating one inside the ViewModel.</p><pre>import Foundation<br><br>final class ProductViewModel {<br>    private let productService: ProductService<br>    <br>    var products: [Product] = []<br>    var errorMessage: String?<br>    var onUpdate: (() -&gt; Void)?<br>    <br>    // 💉 Dependency Injection through initializer<br>    init(productService: ProductService) {<br>        self.productService = productService<br>    }<br>    <br>    func fetchProducts() {<br>        productService.fetchProducts { [weak self] result in<br>            switch result {<br>            case .success(let products):<br>                self?.products = products<br>                self?.errorMessage = nil<br>            case .failure(let error):<br>                self?.products = []<br>                self?.errorMessage = error.localizedDescription<br>            }<br>            self?.onUpdate?()<br>        }<br>    }<br>}</pre><p>Now the ViewModel doesn’t care <strong>where data comes from</strong> — only that it gets it.</p><h3>🖥️ Step 6: The UIKit ViewController</h3><p>We’ll inject our ViewModel into this simple UITableViewController.</p><pre>import UIKit<br><br>final class ProductViewController: UIViewController, UITableViewDataSource {<br>    <br>    private let viewModel: ProductViewModel<br>    private let tableView = UITableView()<br>    <br>    // 💉 Inject the ViewModel from outside<br>    init(viewModel: ProductViewModel) {<br>        self.viewModel = viewModel<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>    <br>    required init?(coder: NSCoder) { fatalError(&quot;init(coder:) not implemented&quot;) }<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        title = &quot;Products&quot;<br>        view.backgroundColor = .systemBackground<br>        setupTableView()<br>        <br>        viewModel.onUpdate = { [weak self] in<br>            DispatchQueue.main.async { self?.tableView.reloadData() }<br>        }<br>        <br>        viewModel.fetchProducts()<br>    }<br>    <br>    private func setupTableView() {<br>        view.addSubview(tableView)<br>        tableView.frame = view.bounds<br>        tableView.dataSource = self<br>    }<br>    <br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        return viewModel.products.count<br>    }<br>    <br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)<br>        -&gt; UITableViewCell {<br>        let cell = UITableViewCell(style: .default, reuseIdentifier: nil)<br>        cell.textLabel?.text = viewModel.products[indexPath.row].name<br>        return cell<br>    }<br>}</pre><h3>🏁 Step 7: Inject Dependencies in SceneDelegate</h3><p>This is where the injection actually happens:</p><pre>func scene(_ scene: UIScene,<br>           willConnectTo session: UISceneSession,<br>           options connectionOptions: UIScene.ConnectionOptions) {<br>    guard let windowScene = (scene as? UIWindowScene) else { return }<br>    <br>    let window = UIWindow(windowScene: windowScene)<br>    <br>    // 💉 Inject the real dependency<br>    let viewModel = ProductViewModel(productService: APIManager())<br>    let viewController = ProductViewController(viewModel: viewModel)<br>    <br>    window.rootViewController = UINavigationController(rootViewController: viewController)<br>    window.makeKeyAndVisible()<br>    self.window = window<br>}</pre><p>This line makes it easy to <strong>swap</strong> dependencies — <br> For example, during testing you can inject MockProductService() instead of APIManager().</p><h3>🧪 Step 8: Unit Testing the ViewModel</h3><p>Here’s where DI shines — testing is simple and clean.</p><pre>import XCTest<br>@testable import YourAppTargetName<br><br>final class ProductViewModelTests: XCTestCase {<br>    <br>    func testFetchProducts_Success() {<br>        let mockService = MockProductService()<br>        let viewModel = ProductViewModel(productService: mockService)<br>        <br>        let expectation = XCTestExpectation(description: &quot;Fetch products successfully&quot;)<br>        <br>        viewModel.onUpdate = {<br>            XCTAssertEqual(viewModel.products.count, 2)<br>            XCTAssertNil(viewModel.errorMessage)<br>            expectation.fulfill()<br>        }<br>        <br>        viewModel.fetchProducts()<br>        wait(for: [expectation], timeout: 1.0)<br>    }<br>    <br>    func testFetchProducts_Failure() {<br>        let mockService = MockProductService()<br>        mockService.shouldReturnError = true<br>        let viewModel = ProductViewModel(productService: mockService)<br>        <br>        let expectation = XCTestExpectation(description: &quot;Fetch products with failure&quot;)<br>        <br>        viewModel.onUpdate = {<br>            XCTAssertTrue(viewModel.products.isEmpty)<br>            XCTAssertNotNil(viewModel.errorMessage)<br>            expectation.fulfill()<br>        }<br>        <br>        viewModel.fetchProducts()<br>        wait(for: [expectation], timeout: 1.0)<br>    }<br>}</pre><p>✅ The tests run instantly — no real network calls, no fragile setup.</p><h3>✅ SwiftUI setup</h3><p><strong>Replace from the Step 5 onwards</strong></p><h4>5️⃣ ViewModel (inject dependency here)</h4><pre>final class ProductViewModel: ObservableObject {<br>    @Published var products: [Product] = []<br>    private let productService: ProductService<br><br>// ✅ Dependency Injection through initializer<br>    init(productService: ProductService) {<br>        self.productService = productService<br>    }<br><br>func loadProducts() {<br>        productService.fetchProducts { [weak self] products in<br>            DispatchQueue.main.async {<br>                self?.products = products<br>            }<br>        }<br>    }<br>}</pre><h4>6️⃣ SwiftUI View (for demo)</h4><pre>import SwiftUI<br><br>struct ProductListView: View {<br>@StateObject var viewModel: ProductViewModel<br><br>var body: some View {<br>        List(viewModel.products, id: \.id) { product in<br>            Text(product.name)<br>        }<br>        .onAppear {<br>            viewModel.loadProducts()<br>        }<br>        .navigationTitle(&quot;Products&quot;)<br>    }<br>}</pre><h4>7️⃣ App Entry Point (inject the dependency)</h4><pre>@main<br>struct DIExampleApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            // 💉 Inject the real dependency here<br>            ProductListView(viewModel: ProductViewModel(productService: APIManager()))<br>            <br>            // OR inject mock for testing:<br>            // ProductListView(viewModel: ProductViewModel(productService: MockProductService()))<br>        }<br>    }<br>}</pre><h3>💡 Understanding onUpdate in Your ViewModel</h3><p>In many MVVM (Model–View–ViewModel) architectures, you’ll see a line like this:</p><pre>var onUpdate: (() -&gt; Void)?</pre><p>At first glance, this might look confusing — but it’s one of the simplest and most flexible ways to let your <strong>ViewModel</strong> talk back to your <strong>View</strong>.</p><p>Let’s break it down.</p><h3>🧠 What Does onUpdate Mean?</h3><p>onUpdate is an <strong>optional closure</strong>.<br> In Swift, a closure is just a block of code you can store in a variable and run later.</p><p>Here’s what this specific type means:</p><pre>(() -&gt; Void)?</pre><ul><li>() → it takes no parameters</li><li>Void → it doesn’t return anything</li><li>? → it’s optional — it might be nil</li></ul><p>So, onUpdate is a variable that <em>can hold some code to execute later</em>, or it can be nil if no one has set it yet.</p><h3>⚙️ How It Works Inside the ViewModel</h3><p>Take this typical method:</p><pre>func fetchProducts() {<br>    productService.fetchProducts { [weak self] result in<br>        switch result {<br>        case .success(let products):<br>            self?.products = products<br>            self?.errorMessage = nil<br>        case .failure(let error):<br>            self?.products = []<br>            self?.errorMessage = error.localizedDescription<br>        }<br>        self?.onUpdate?() // &lt;-- triggers UI update<br>    }<br>}</pre><p>When data fetching is done, the ViewModel calls onUpdate?().<br> That’s Swift shorthand for:</p><blockquote><em>“If </em><em>onUpdate is not </em><em>nil, call it.”</em></blockquote><p>It’s the ViewModel’s way of saying:</p><blockquote><em>“Hey View, I’ve got new data — update yourself!”</em></blockquote><h3>🕒 Why Order Matters</h3><p>Consider the following two versions:</p><h4>✅ Version 1 — The Right Way</h4><pre>viewModel.onUpdate = {<br>    print(&quot;UI updated&quot;)<br>}<br>viewModel.fetchProducts()</pre><p>Here, you <strong>assign the closure first</strong>.<br> So when fetchProducts() finishes and calls onUpdate?(), your closure is already set — everything works as expected.</p><h4>⚠️ Version 2 — The Risky Way</h4><pre>viewModel.fetchProducts()<br>viewModel.onUpdate = {<br>    print(&quot;UI updated&quot;)<br>}</pre><p>At first, this might <em>seem</em> fine — especially if your network call is asynchronous.<br> But here’s what actually happens step by step:</p><ol><li>fetchProducts() starts fetching.</li><li>onUpdate is still nil.</li><li>The service finishes quickly (maybe using cached data).</li><li>self?.onUpdate?() executes — but onUpdate is nil, so nothing happens.</li><li>Then you assign onUpdate, but it’s too late. The update signal was already missed.</li></ol><p>So the ViewModel “rang the bell,” but the View hadn’t installed the doorbell yet.</p><h3>🔍 Why It Usually Works Anyway</h3><p>Most network calls are <strong>asynchronous</strong>, meaning they take a bit of time.<br> So by the time the fetch completes, you’ve probably already set onUpdate.<br> That’s why the issue doesn’t always appear — but it’s still a <strong>timing risk</strong>.</p><p>If your ProductService ever returns data <em>synchronously</em> (e.g., from cache or mock data), your closure will never run.</p><h3>✅ Best Practice</h3><p>Always set your callback <em>before</em> triggering the action that depends on it:</p><pre>viewModel.onUpdate = { [weak self] in<br>    self?.updateUI()<br>}<br>viewModel.fetchProducts()</pre><p>This guarantees your View is listening before the ViewModel starts sending updates.<br> It’s predictable, safe, and works in both async and sync cases.</p><h3>🧩 Why We Usually Avoid Singleton for APIManager in Dependency Injection</h3><h3>❌ The Singleton Way (Tightly Coupled)</h3><p>A common (but problematic) pattern:</p><pre>final class APIManager {<br>    static let shared = APIManager() // Singleton<br>    <br>    func fetchProducts() {<br>        print(&quot;Fetching products from server…&quot;)<br>    }<br>}<br><br>final class ProductViewModel {<br>    func load() {<br>        APIManager.shared.fetchProducts() // Directly using singleton<br>    }<br>}</pre><h4>Issues:</h4><ol><li><strong>Hard to test</strong> — you can’t replace APIManager.shared with a mock.</li><li><strong>Tight coupling</strong> — your ViewModel <em>depends</em> on a global object.</li><li><strong>Hidden dependency</strong> — not visible in the ViewModel’s initializer.</li><li><strong>Difficult to scale</strong> — what if you need a different APIManager (e.g. staging vs production)?</li></ol><h3>✅ The Dependency Injection Way (Loosely Coupled)</h3><pre>protocol ProductService {<br>    func fetchProducts()<br>}<br><br>final class APIManager: ProductService {<br>    func fetchProducts() {<br>        print(&quot;Fetching products from server…&quot;)<br>    }<br>}<br><br>final class ProductViewModel {<br>    private let productService: ProductService<br>    <br>    init(productService: ProductService) { // Dependency injected<br>        self.productService = productService<br>    }<br>    <br>    func load() {<br>        productService.fetchProducts()<br>    }<br>}</pre><p>Now you can do:</p><pre>let viewModel = ProductViewModel(productService: APIManager()) // Real<br>let testVM   = ProductViewModel(productService: MockService()) // Mock</pre><p>✅ Testable<br> ✅ Reusable<br> ✅ No hidden global state</p><h3>🧩 Final Thoughts</h3><p>Dependency Injection might sound intimidating at first,<br> but it’s simply a way to write <strong>clean, decoupled, and testable Swift code</strong>.</p><p>Once you get used to injecting dependencies instead of creating them,<br> you’ll never want to go back.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb67b2c88fb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Understanding Singleton Class Memory Management and Thread Safety in Swift]]></title>
            <link>https://medium.com/@iamCoder/understanding-singleton-class-memory-management-and-thread-safety-in-swift-922e3c3b63c9?source=rss-1cde0ddee7b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/922e3c3b63c9</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Adam Dev]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 14:34:48 GMT</pubDate>
            <atom:updated>2025-11-08T03:31:49.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CB-avojxI82iBFwSBd0iug.png" /></figure><p>The <strong>Singleton pattern</strong> is one of the most common design patterns in iOS development — especially for managing shared services like networking, caching, or user sessions.</p><p>But with great power comes great responsibility: if you’re not careful, a singleton can easily lead to memory leaks or concurrency issues.</p><p>Let’s break it down step-by-step 👇</p><h3>🧩 What is a Singleton?</h3><p>A <strong>singleton</strong> ensures that only <strong>one instance</strong> of a class exists throughout the entire app lifecycle.</p><pre>class NetworkManager {<br>    static let shared = NetworkManager()<br>    private init() { } // prevents creating another instance<br>}</pre><p>Usage:</p><pre>NetworkManager.shared // always returns the same instance</pre><p>✅ You can access NetworkManager.shared from anywhere in your code, and it always refers to the same object.</p><h3>⚙️ How Singleton Works in Memory</h3><p>When you declare:</p><pre>static let shared = NetworkManager()</pre><p>Swift does the following:</p><ul><li>Creates the instance <strong>lazily</strong>, only when first accessed.</li><li>Stores it in <strong>static memory</strong> (similar to a global constant).</li><li>Keeps it in memory for the <strong>entire lifetime of the app</strong>.</li></ul><p>Even if you set your own references to nil, the shared instance will stay alive until the app terminates.</p><h3>🧠 Memory Management Details (ARC)</h3><p>Swift uses <strong>Automatic Reference Counting (ARC)</strong> to manage memory.</p><p>For a singleton:</p><pre>static let shared = NetworkManager()</pre><ul><li>shared is a <strong>strong reference</strong> owned by the class type itself.</li><li>The instance’s reference count never drops to zero.</li><li>Therefore, it’s <strong>never deallocated</strong> automatically.</li></ul><p>In short:</p><blockquote><strong><em>A singleton lives for the entire app lifecycle.</em></strong></blockquote><h3>⚠️ Common Memory Leak Pitfalls</h3><p>A singleton can easily cause leaks if it <strong>strongly retains other objects</strong> — especially delegates or closures.</p><p>Example (❌):</p><pre>class NetworkManager {<br>    static let shared = NetworkManager()<br>    var delegate: ViewController? // strong reference causes leak<br>}</pre><p>Correct approach (✅):</p><pre>class NetworkManager {<br>    static let shared = NetworkManager()<br>    weak var delegate: ViewController?<br>}</pre><p>👉 Always use weak or unowned for delegates or long-lived references.</p><h3>⚠️ Why Singletons Can Easily Cause Memory Leaks</h3><p>Singletons are a common pattern in iOS apps — a single, shared instance that lives <strong>for the entire lifetime of your app</strong>:</p><pre>final class DataManager {<br>    static let shared = DataManager()<br>    private init() {}<br>}</pre><p>Because a singleton <strong>never goes away</strong>, any object it <strong>strongly retains</strong> will also live forever. If that object is a <strong>delegate, closure, or view controller</strong>, it can’t be released even when you no longer need it — and that’s a memory leak.</p><h3>🔹 Example: Strongly Captured Delegate</h3><pre>protocol DataManagerDelegate: AnyObject {<br>    func dataDidUpdate()<br>}<br>final class DataManager {<br>    static let shared = DataManager()<br>    private init() {}<br><br>var delegate: DataManagerDelegate? // ⚠️ strong reference by default<br><br>}</pre><p>If a view controller sets itself as the delegate:</p><pre>class MyViewController: UIViewController, DataManagerDelegate {<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        DataManager.shared.delegate = self<br>    }<br> func dataDidUpdate() { ... }<br>}</pre><p>The chain looks like this:</p><pre>DataManager.shared → strong reference → MyViewController</pre><p>Because the singleton lives forever, the ViewController <strong>can never be deallocated</strong> — even after it’s dismissed.</p><p><strong>Fix:</strong> Use a weak reference:</p><pre>weak var delegate: DataManagerDelegate?</pre><h3>🔹 Example: Closure Capturing self</h3><pre>DataManager.shared.completion = {<br>    self.doSomething() // ⚠️ strong capture of self<br>}</pre><p>Here’s the reference chain:</p><pre>DataManager.shared → strong reference → closure → strong reference → ViewController</pre><ul><li>The singleton holds the closure.</li><li>The closure holds the view controller.</li><li>The view controller <strong>cannot be released</strong>, causing a memory leak.</li></ul><p><strong>Fix:</strong> Use [weak self] in the closure:</p><pre>DataManager.shared.completion = { [weak self] in<br>    self?.doSomething()<br>}</pre><p>Now the closure doesn’t strongly hold the view controller, so it can be released normally.</p><h3>💡 Super Simple Analogy</h3><ul><li><strong>Singleton</strong> → “forever keeper”</li><li><strong>Closure / delegate</strong> → “friend that talks to the keeper”</li><li><strong>ViewController / object</strong> → “thing you want to remove”</li></ul><p>If the keeper holds a strong grip on the friend, and the friend holds a strong grip on the object, the object <strong>can’t leave</strong>. Using weak references is like letting go of that grip.</p><h3>🧾 Memory Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*_qrm-6f-fkazoEygeF8iUg.png" /></figure><h3>🧵 Making a Singleton Thread-Safe</h3><p>Now that we understand memory management, let’s address another big concern — <strong>thread safety</strong>.</p><h3>✅ Initialization Is Already Thread-Safe</h3><p>Swift guarantees that static let initialization is <strong>atomic and thread-safe</strong>.</p><pre>final class DataManager {<br>    static let shared = DataManager()<br>    private init() { }<br>}</pre><p>Even if multiple threads try to access shared at the same time, Swift ensures it’s only initialized once.</p><p>So you <strong>don’t need</strong> old-school dispatch_once anymore.</p><h3>⚠️ But Usage May Not Be Thread-Safe</h3><p>Initialization is safe, but <strong>accessing mutable data</strong> inside your singleton may not be.</p><p>Example:</p><pre>DispatchQueue.global().async {<br>    DataManager.shared.addItem(&quot;A&quot;)<br>}<br>DispatchQueue.global().async {<br>    DataManager.shared.addItem(&quot;B&quot;)<br>}</pre><p>If both threads modify a shared array, you can hit <strong>race conditions</strong> or <strong>crashes</strong>.</p><h3>🔒 Making It Thread-Safe</h3><h3>Option 1: Use a Serial Dispatch Queue (Recommended)</h3><pre>final class DataManager {<br>    static let shared = DataManager()<br>    private init() { }<br><br>    private var items: [String] = []<br>    private let queue = DispatchQueue(label: &quot;com.example.DataManagerQueue&quot;)<br><br>func addItem(_ item: String) {<br>        queue.async {<br>            self.items.append(item)<br>        }<br>    }<br><br>func getItems(completion: @escaping ([String]) -&gt; Void) {<br>        queue.async {<br>            completion(self.items)<br>        }<br>    }<br>}</pre><p>✅ Ensures only one thread accesses items at a time<br> ✅ No race conditions<br> ✅ Modern, Swift-friendly</p><h3>Option 2: Use Locks (Low-Level Alternative)</h3><pre>final class DataManager {<br>    static let shared = DataManager()<br>    private init() { }<br><br>private var items: [String] = []<br>    private let lock = NSLock()<br><br>func addItem(_ item: String) {<br>        lock.lock()<br>        items.append(item)<br>        lock.unlock()<br>    }<br><br>func getItems() -&gt; [String] {<br>        lock.lock()<br>        defer { lock.unlock() }<br>        return items<br>    }<br>}</pre><p>Useful if you need <strong>fine-grained control</strong> or can’t afford async behavior.</p><h3>🧾 Thread Safety Summary</h3><p>Safety LevelTechniqueNotesInitializationstatic letAlready thread-safeAccessSerial DispatchQueueRecommendedAccess (alt)NSLockFor low-level controlGlobal varsAvoidNot always thread-safe</p><h3>🚀 Final Thoughts</h3><p>Singletons are simple but powerful tools.<br> However, misuse can easily lead to memory leaks or concurrency issues.</p><p><strong>Key takeaways:</strong></p><ul><li>Use static let for thread-safe initialization.</li><li>Avoid retaining other objects strongly.</li><li>Use a serial queue or lock for safe read/write access.</li><li>Keep singletons lightweight and focused.</li></ul><p>Used wisely, singletons can make your architecture clean and predictable — without the hidden memory or threading traps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=922e3c3b63c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Actors in Swift: Thread-Safety Made Simple]]></title>
            <link>https://medium.com/@iamCoder/understanding-actors-in-swift-thread-safety-made-simple-190dad9f866d?source=rss-1cde0ddee7b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/190dad9f866d</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Adam Dev]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 10:18:35 GMT</pubDate>
            <atom:updated>2025-09-17T10:18:35.640Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift introduced <strong>actors</strong> in Swift 5.5 as part of the new concurrency model. If you’ve ever struggled with thread safety or locking, actors are here to make your life easier. They let you write concurrent code without worrying about data races — and the compiler even helps enforce the rules.</p><p>In this article, we’ll break down what actors are, why await is required, and how to use them effectively.</p><h3>🔹 What is an Actor?</h3><p>An <strong>actor</strong> is like a class that protects its mutable state. Instead of you manually adding locks or queues, Swift automatically ensures that only <strong>one task at a time</strong> can access an actor’s data.</p><p>Think of an actor as a small, isolated world:</p><ul><li>Inside, you can freely mutate state.</li><li>From the outside, you must <strong>await your turn</strong> to enter.</li></ul><h3>🔹 Actor Example</h3><pre>actor Counter {<br>    private var value = 0<br>    <br>    func increment() {<br>        value += 1<br>    }<br>    <br>    func getValue() -&gt; Int {<br>        return value<br>    }<br>}<br><br>let counter = Counter()<br><br>Task {<br>    await counter.increment()<br>    let current = await counter.getValue()<br>    print(current) // prints 1<br>}</pre><p>Here’s what’s happening:</p><ul><li>value is safe from data races.</li><li>Calls like increment() and getValue() require await from outside the actor.</li><li>The actor serializes access behind the scenes.</li></ul><h3>🔹 Why await is Required</h3><p>When you call an actor’s method from the outside, Swift forces you to use await.</p><pre>let counter = Counter()<br><br>Task {<br>    await counter.increment()    // ✅ must use await<br>    print(await counter.value)   // ✅ must use await<br>}</pre><p>Why? Because multiple tasks may want to access the actor at the same time. Swift queues up those calls and runs them <strong>one by one</strong>. Your code may need to <strong>wait</strong> until the actor is available, so await makes that explicit.</p><h3>🔹 Inside vs Outside an Actor</h3><ul><li><strong>Inside the actor</strong>: You can directly access its properties and methods, no await needed.</li></ul><pre>actor Counter {<br><br>var value = 0<br><br>func increment() {<br><br>value += 1 // direct access<br><br>}<br><br>}</pre><ul><li><strong>Outside the actor</strong>: Calls require await.</li></ul><pre>Task {<br><br>await counter.increment()<br><br>}</pre><h3>🔹 Nonisolated Methods</h3><p>Sometimes you want a method that doesn’t touch the actor’s state and doesn’t need await. That’s where nonisolated comes in:</p><pre>actor Counter {<br>    var value = 0<br>    <br>    nonisolated func description() -&gt; String {<br>        return &quot;Counter actor&quot;<br>    }<br>}</pre><p>⚠️ But be careful: nonisolated methods <strong>cannot access the actor’s stored properties</strong>. They’re safe to call synchronously, but isolated data is off-limits.</p><h3>🔹 Computed Properties</h3><p>Even computed properties are async if they depend on isolated state:</p><pre>actor Counter {<br>    var value = 0<br>    var doubled: Int { value * 2 }<br>}<br><br>Task {<br>    let d = await counter.doubled  // still requires await<br>}</pre><h3>🔹 Actor vs Class</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*_Z4f8qUakYPz7wg0zxyBcA.png" /></figure><h3>🔹 Real-World Example: Network Request Manager</h3><p>Let’s say you’re building an app that makes multiple API calls simultaneously. Without careful synchronization, you might end up with race conditions or duplicate requests. An actor can help coordinate this safely:</p><pre>actor NetworkManager {<br>private var activeRequests: [String: Task&lt;Data, Error&gt;] = [:]<br><br><br>func fetch(url: URL) async throws -&gt; Data {<br>let key = url.absoluteString<br><br><br>// If a request for this URL already exists, return it<br>if let existing = activeRequests[key] {<br>return try await existing.value<br>}<br><br><br>// Otherwise, start a new request<br>let task = Task {<br>let (data, _) = try await URLSession.shared.data(from: url)<br>return data<br>}<br><br><br>activeRequests[key] = task<br><br><br>do {<br>let data = try await task.value<br>activeRequests[key] = nil // cleanup<br>return data<br>} catch {<br>activeRequests[key] = nil // cleanup on failure<br>throw error<br>}<br>}<br>}</pre><h4>Usage:</h4><pre>let manager = NetworkManager()<br><br>Task {<br><br>let url = URL(string: &quot;https://example.com/data.json&quot;)!<br><br>let data = try await manager.fetch(url: url)<br><br>print(&quot;Fetched data: \(data.count) bytes&quot;)<br><br>}</pre><p>Here, the actor ensures that requests for the same URL don’t overlap. Multiple tasks can safely share the same NetworkManager instance without data races.</p><h4>❌ Without Actor (NSLock)</h4><pre>class NetworkManagerWithLock {<br>private var activeRequests: [String: Task&lt;Data, Error&gt;] = [:]<br>private let lock = NSLock()<br><br><br>func fetch(url: URL) async throws -&gt; Data {<br>let key = url.absoluteString<br><br><br>lock.lock()<br>if let existing = activeRequests[key] {<br>lock.unlock()<br>return try await existing.value<br>}<br><br><br>let task = Task {<br>let (data, _) = try await URLSession.shared.data(from: url)<br>return data<br>}<br>activeRequests[key] = task<br>lock.unlock()<br><br><br>do {<br>let data = try await task.value<br>lock.lock(); activeRequests[key] = nil; lock.unlock()<br>return data<br>} catch {<br>lock.lock(); activeRequests[key] = nil; lock.unlock()<br>throw error<br>}<br>}<br>}</pre><p>Here we had to:</p><ul><li>Introduce a lock to protect shared state.</li><li>Carefully lock/unlock around each access.</li><li>Manually ensure cleanup is thread-safe</li></ul><h4>❌ Without Actor (DispatchQueue)</h4><pre>class NetworkManagerWithQueue {<br>private var activeRequests: [String: Task&lt;Data, Error&gt;] = [:]<br>private let queue = DispatchQueue(label: &quot;network.manager.queue&quot;, attributes: .concurrent)<br><br><br>func fetch(url: URL) async throws -&gt; Data {<br>let key = url.absoluteString<br><br><br>return try await withCheckedThrowingContinuation { continuation in<br>queue.async(flags: .barrier) {<br>if let existing = self.activeRequests[key] {<br>Task {<br>do {<br>let data = try await existing.value<br>continuation.resume(returning: data)<br>} catch {<br>continuation.resume(throwing: error)<br>}<br>}<br>return<br>}<br><br><br>let task = Task {<br>let (data, _) = try await URLSession.shared.data(from: url)<br>return data<br>}<br>self.activeRequests[key] = task<br><br><br>Task {<br>do {<br>let data = try await task.value<br>self.queue.async(flags: .barrier) { self.activeRequests[key] = nil }<br>continuation.resume(returning: data)<br>} catch {<br>self.queue.async(flags: .barrier) { self.activeRequests[key] = nil }<br>continuation.resume(throwing: error)<br>}<br>}<br>}<br>}<br>}<br>}</pre><p>Here we had to:</p><ul><li>Use a barrier to make writes exclusive.</li><li>Wrap async results with withCheckedThrowingContinuation to bridge into async/await.</li><li>Carefully manage cleanup.</li></ul><h3>✅ Key Takeaways</h3><ul><li>Actors are like classes with <strong>built-in thread safety</strong>.</li><li>They protect state by ensuring <strong>serialized access</strong>.</li><li>You must use await when calling into an actor from outside.</li><li>nonisolated lets you define sync methods, but they can’t touch protected data.</li></ul><p>Actors are a cornerstone of Swift’s concurrency model — giving you safety without the complexity of locks and manual synchronization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=190dad9f866d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding nonisolated, nonisolated(nonsending), and @concurrent in Swift 6.2]]></title>
            <link>https://medium.com/@iamCoder/understanding-nonisolated-nonisolated-nonsending-and-concurrent-in-swift-6-2-388b34f4fe4d?source=rss-1cde0ddee7b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/388b34f4fe4d</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Adam Dev]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 09:04:08 GMT</pubDate>
            <atom:updated>2025-09-17T09:04:08.483Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpqGpGA9fwkZUhhatqXV-A.png" /></figure><p>Swift 6.2 introduced several improvements to concurrency, and two keywords you’ll see a lot are nonisolated(nonsending) and @concurrent. These additions were designed to make Swift’s concurrency model easier to reason about and less confusing than in earlier versions.</p><p>In this article, I’ll break down what these keywords mean, why they exist, and when you should use them — in plain English.</p><h3>The confusion with nonisolated (before Swift 6.2)</h3><p>Let’s start with nonisolated. Normally, when you put a function inside an actor (or a @MainActor class), Swift makes that function <strong>isolated</strong>. That means you can only access it through Swift’s concurrency rules — usually with await — to keep things thread-safe.</p><p>But sometimes you want a function that doesn’t touch the actor’s state and should be callable from anywhere, without await. That’s when you mark it as nonisolated.</p><p>Sounds simple, right? The confusing part is that before Swift 6.2, the behavior of nonisolated depended on whether the function was async or not:</p><ul><li>nonisolated async → automatically ran in the <strong>background</strong> (global executor).</li><li>nonisolated non-async → ran on the <strong>caller’s actor</strong> (e.g., the main actor if called from the main thread).</li></ul><p>Same keyword, two different behaviors. That was unintuitive and often surprising.</p><h3>Fixing the confusion: nonisolated(nonsending)</h3><p>Swift 6.2 fixes this inconsistency with a new keyword: nonisolated(nonsending).</p><p>When you use this, it means:</p><p>👉 “Run this function on the <strong>caller’s actor</strong> no matter what.”</p><p>This way, both async and non-async functions behave the same. There’s no hidden offloading to the global executor, and your code becomes easier to reason about.</p><p>Another bonus: because you’re not jumping to a new isolation domain, you don’t have to make everything Sendable. Less boilerplate, less complexity.</p><p>You can even enable the <strong>NonIsolatedNonSendingByDefault</strong> flag in Swift 6.2, which makes all nonisolated functions behave this way unless you say otherwise.</p><h3>Offloading work: @concurrent</h3><p>Now, what if you actually <em>do</em> want to push a function onto a background thread? For example, decoding a huge JSON response that would block the main thread?</p><p>That’s where @concurrent comes in.</p><p>When you mark a function as @concurrent, you’re saying:</p><p>👉 “Always run this function on the <strong>global executor</strong> (background thread).”</p><p>Example:</p><pre>@concurrent<br>func decode&lt;T: Decodable&gt;(_ data: Data) async throws -&gt; T {<br>    let decoder = JSONDecoder()<br>    return try decoder.decode(T.self, from: data)<br>}</pre><p>Here, decode will never run on the main actor. Instead, it always offloads to the background, so your UI stays responsive.</p><p>Note: @concurrent automatically makes a function nonisolated, so you don’t need to write both.</p><h3>When to use which?</h3><p>Here’s a simple guide:</p><ul><li><strong>nonisolated(nonsending)</strong> → Use this when your function doesn’t touch actor state and should just run in the <strong>same place as the caller</strong>. This is the safe, default option that avoids extra complexity.</li><li><strong>@concurrent</strong> → Use this when the function does heavy CPU work (like JSON decoding or image processing) that shouldn’t block the caller’s actor. It runs on the <strong>background thread</strong>.</li></ul><h3>Real-world example</h3><pre>actor Networking {<br>    // Runs where the caller is (main actor if called from UI)<br>    nonisolated(nonsending)<br>    func helper() -&gt; String {<br>        &quot;Just a helper function&quot;<br>    }<br><br>// Network call already suspends, no need for @concurrent<br>    func loadData(from url: URL) async throws -&gt; Data {<br>        let (data, _) = try await URLSession.shared.data(from: url)<br>        return data<br>    }<br><br>// Heavy JSON decoding → use @concurrent to offload<br>    @concurrent<br>    func decode&lt;T: Decodable&gt;(_ data: Data) async throws -&gt; T {<br>        let decoder = JSONDecoder()<br>        return try decoder.decode(T.self, from: data)<br>    }<br>}</pre><p>In this setup:</p><ul><li>helper() is simple and stays on the caller’s actor.</li><li>loadData is async, so while waiting on the network, the main actor is free.</li><li>decode is heavy, so it’s marked @concurrent to run in the background.</li></ul><h3>Wrapping up</h3><ul><li>nonisolated lets you escape actor isolation.</li><li>Before Swift 6.2, its behavior was inconsistent between async and non-async functions.</li><li>nonisolated(nonsending) fixes that by always running on the caller’s actor.</li><li>@concurrent makes your intent explicit when you <em>do</em> want background execution.</li></ul><p>Think of it this way:</p><ul><li>nonisolated(nonsending) = <em>“Stay here and run where I called you.”</em></li><li>@concurrent = <em>“Go to the background and don’t block me.”</em></li></ul><p>Use concurrency only where it’s really needed — it makes apps faster but also adds complexity. The new Swift 6.2 tools help you be more precise about where and when to introduce it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=388b34f4fe4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding MainActor and nonisolated in Swift: A Beginner-Friendly Guide]]></title>
            <link>https://medium.com/@iamCoder/understanding-mainactor-in-swift-a-beginner-friendly-guide-075ec924d0ef?source=rss-1cde0ddee7b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/075ec924d0ef</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Adam Dev]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 11:17:34 GMT</pubDate>
            <atom:updated>2025-09-16T11:56:20.854Z</atom:updated>
            <content:encoded><![CDATA[<p>When building iOS or macOS apps, one of the most important rules is:</p><p>👉 <strong>All UI updates must happen on the main thread.</strong></p><p>If you update the UI from a background thread, your app can crash or behave strangely. That’s where <strong>MainActor</strong> comes in.</p><p>In this article, we’ll break down MainActor, compare it to DispatchQueue.main, and walk through examples that make the concept easy to understand.</p><h3>What is MainActor?</h3><p>In Swift, <strong>actors</strong> are types that protect their data from being accessed by multiple threads at once. This prevents race conditions and makes your code thread-safe.</p><p>The <strong>MainActor</strong> is a special, built-in actor that ensures any code you run inside it will always execute on the <strong>main thread</strong>.</p><p>This is especially useful for UI code because UIKit, AppKit, and SwiftUI all require UI updates on the main thread.</p><h3>Why not just use DispatchQueue.main?</h3><p>Before Swift Concurrency (async/await, actors, Task), developers used <strong>Grand Central Dispatch (GCD)</strong> to run code on the main thread:</p><pre>DispatchQueue.main.async {<br>    label.text = &quot;Hello!&quot;<br>}</pre><p>This works, but it has drawbacks:</p><ul><li>You must <strong>manually wrap</strong> UI updates inside DispatchQueue.main.async.</li><li>The <strong>compiler won’t warn you</strong> if you accidentally update UI from the wrong thread.</li><li>It doesn’t integrate well with Swift’s new concurrency system.</li></ul><h3>Benefits of MainActor</h3><p>With MainActor, you get:</p><p>✅ Cleaner code (less boilerplate).<br> ✅ Compiler checks to prevent UI updates off the main thread.<br> ✅ Seamless integration with Swift Concurrency (async/await, Task, actor).</p><h3>How to Use MainActor</h3><h3>1. Annotate a function</h3><pre>@MainActor<br>func updateUI() {<br>    label.text = &quot;Updated!&quot;<br>}</pre><p>This guarantees that updateUI() always runs on the main thread.</p><h3>2. Annotate a class or struct</h3><pre>@MainActor<br>class ViewModel {<br>    var text: String = &quot;&quot;<br>}</pre><p>Now <strong>all methods and properties</strong> inside ViewModel are automatically main-thread safe.</p><h3>3. Use MainActor.run</h3><pre>Task {<br>    let data = await fetchData()<br>    await MainActor.run {<br>        label.text = data<br>    }<br>}</pre><p>This is handy when you just want to temporarily switch back to the main thread.</p><h3>Comparing DispatchQueue.main vs MainActor</h3><p>Let’s see a side-by-side example.</p><h3>🟠 Using DispatchQueue.main</h3><pre>func loadData() {<br>    Task {<br>        let data = await fetchData()   // background work<br>        DispatchQueue.main.async {     // switch to main thread manually<br>            self.label.text = data     // update UI<br>        }<br>    }<br>}</pre><ul><li>Works fine.</li><li>Easy to forget wrapping UI updates.</li><li>Compiler won’t warn you if you forget.</li></ul><h3>🟢 Using MainActor</h3><pre>@MainActor<br>func updateUI(with data: String) {<br>    self.label.text = data<br>}<br><br>func loadData() {<br>    Task {<br>        let data = await fetchData()<br>        await updateUI(with: data)   // compiler enforces main-thread<br>    }<br>}</pre><ul><li>Cleaner and safer.</li><li>Compiler guarantees main-thread execution.</li></ul><h3>Example fetchData() Function</h3><p>Here’s a simple async function that simulates loading data:</p><pre>func fetchData() async -&gt; String {<br>    // Simulate a slow task (like a network call)<br>    try? await Task.sleep(nanoseconds: 2_000_000_000) // 2 seconds<br>    return &quot;Hello from server!&quot;<br>}</pre><p>In a real-world app, you might fetch data from the network:</p><pre>func fetchData() async -&gt; String {<br>    let url = URL(string: &quot;https://example.com/data.txt&quot;)!<br>    let (data, _) = try! await URLSession.shared.data(from: url)<br>    return String(data: data, encoding: .utf8) ?? &quot;No data&quot;<br>}</pre><h3>Full Working SwiftUI Example</h3><p>Here’s a tiny app that puts everything together:</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    @State private var message = &quot;Loading...&quot;<br><br>var body: some View {<br>        VStack(spacing: 20) {<br>            Text(message)<br>                .font(.title)<br>            Button(&quot;Load Data&quot;) {<br>                loadData()<br>            }<br>        }<br>        .padding()<br>    }<br><br>func loadData() {<br>        Task {<br>            let data = await fetchData()<br>            await MainActor.run {<br>                self.message = data<br>            }<br>        }<br>    }<br><br>func fetchData() async -&gt; String {<br>        try? await Task.sleep(nanoseconds: 2_000_000_000)<br>        return &quot;Hello from server!&quot;<br>    }<br>}</pre><ul><li>Tap <strong>“Load Data”</strong>, it waits 2 seconds, then updates the UI safely using MainActor.</li></ul><h3>Understanding nonisolated</h3><p>By default, when you mark a class, struct, or function with @MainActor (or any actor), everything inside is <strong>actor-isolated</strong>:</p><ul><li>You must use await to call its methods or access properties from outside.</li><li>The compiler enforces this to keep things safe.</li></ul><h3>Example (default behavior)</h3><pre>@MainActor<br>class MyViewModel {<br>var text: String = &quot;Hello&quot;<br><br><br>func updateUI() {<br>print(&quot;UI updated with: \(text)&quot;)<br>}<br>}<br><br><br>let vm = MyViewModel()<br><br><br>Task {<br>await vm.updateUI() // ✅ must use await<br>print(await vm.text) // ✅ also requires await<br>}</pre><h3>Opting out with nonisolated</h3><p>Sometimes, a method or property doesn’t actually depend on the actor’s state. For example, logging or a constant value. In that case, you can mark it as <strong>nonisolated</strong>:</p><pre>@MainActor<br>class MyViewModel {<br>var text: String = &quot;Hello&quot;<br><br><br>nonisolated func logMessage() {<br>print(&quot;Logging something not tied to UI state&quot;)<br>}<br><br><br>nonisolated let id = UUID() // safe: doesn&#39;t touch UI<br>}</pre><h4>Usage</h4><pre>let vm = MyViewModel()<br>vm.logMessage() // ✅ can call from anywhere, no await needed<br>print(vm.id)</pre><h3>Default vs nonisolated</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*LNwKQJxgQWEdVkjRm-qH7w.png" /></figure><h3>Analogy: Kitchen vs Waiter</h3><p>Think of your app like a restaurant:</p><ul><li><strong>Background threads</strong> = kitchen staff (doing heavy work).</li><li><strong>Main thread</strong> = waiter (serves customers/UI).</li><li>If chefs rush to serve food directly, chaos happens.</li><li>MainActor ensures only the waiter (main thread) serves customers.</li></ul><h3>Final Thoughts</h3><ul><li>You <em>can</em> still use DispatchQueue.main, but MainActor is the modern, safer approach.</li><li>With @MainActor, the compiler helps enforce main-thread rules.</li><li>It integrates seamlessly with Swift Concurrency, making your code cleaner and future-proof.</li></ul><p>👉 Use MainActor whenever you’re dealing with <strong>UI updates</strong> or code that must always run on the main thread.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=075ec924d0ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>