<?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 Rajveer on Medium]]></title>
        <description><![CDATA[Stories by Rajveer on Medium]]></description>
        <link>https://medium.com/@raajveer?source=rss-a769be0a8ae0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WgXmZlQNtrkm0sKgLjfI5w.png</url>
            <title>Stories by Rajveer on Medium</title>
            <link>https://medium.com/@raajveer?source=rss-a769be0a8ae0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 01:56:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raajveer/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SwiftUI Ownership vs. Access: Why @Binding Doesn’t Own Your Data]]></title>
            <link>https://medium.com/@raajveer/swiftui-ownership-vs-access-why-binding-doesnt-own-your-data-b68b5aeb1b8d?source=rss-a769be0a8ae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b68b5aeb1b8d</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui-binding]]></category>
            <category><![CDATA[swiftui-state]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Rajveer]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 16:29:46 GMT</pubDate>
            <atom:updated>2026-11-02T16:29:46.190Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0sFColS8ljv1VM_S7JzcZA.png" /></figure><p>One common source of confusion in SwiftUI is the belief that @Binding holds or owns a value. To understand SwiftUI data flow, it is important to distinguish between owning a piece of data and accessing it. Lets explore how @State and @Binding work together, how SwiftUI manages state storage, and why a binding provides two-way access to an existing source of truth rather than creating a copy of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*trJ8FEgypWSJIefF9zx27g.png" /></figure><h3>@State: Owning Local View State</h3><p>@State declares mutable, view-local state in SwiftUI. The view that declares it becomes responsible for that piece of data and acts as its source of truth.</p><p>Although @State is declared as a property of a view, SwiftUI manages its underlying storage. This storage is associated with the view’s identity rather than simply being recreated every time the view’s body is evaluated.</p><h4>Why Should @State Be Private?</h4><p>Apple recommends declaring @State properties as private. This prevents them from being initialized through the view’s memberwise initializer and reinforces that the state belongs to the view declaring it.</p><p>Other views can still receive access to this state through mechanisms such as @Binding.</p><h4>How Does Change Tracking Work?</h4><p>When a @State property changes, SwiftUI invalidates the relevant view and recomputes its body. The updated view hierarchy is then reconciled, and SwiftUI updates the necessary parts of the interface based on their dependencies.</p><p>Consider a simple player interface:</p><pre>struct PlayerView: View {<br>    @State private var isPlaying = false<br><br>    var body: some View {<br>        Button(isPlaying ? &quot;Pause&quot; : &quot;Play&quot;) {<br>            isPlaying.toggle()<br>        }<br>    }<br>}</pre><p>Here, PlayerView owns isPlaying.</p><ul><li><strong>Declaration:</strong> @State establishes the local state.</li><li><strong>Mutation:</strong> isPlaying.toggle() changes its value.</li><li><strong>Update:</strong> SwiftUI detects the change and recomputes the view’s body.</li><li><strong>Result:</strong> The button title changes from “Play” to “Pause”, or vice versa.</li></ul><p>This demonstrates how @State connects mutable data with the interface that depends on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eEyeXGKMN0yIMF70vsDUAw.png" /></figure><h3>@Binding: Accessing Existing State</h3><p>While @State establishes ownership, @Binding provides another view with read-write access to an existing source of truth.</p><p>A binding does not create its own independent storage. Instead, it connects a view to a value managed elsewhere, allowing that view to read and modify the original state.</p><p>A Binding provides two access mechanisms:</p><ul><li><strong>Getter:</strong> Reads the current value from the source of truth.</li><li><strong>Setter:</strong> Forwards changes back to the source of truth.</li></ul><p>This makes binding a two-way connection rather than an independent value.</p><h4>How Do You Pass a Binding?</h4><p>SwiftUI uses the $ prefix to access the projected value of a property wrapper.</p><p>When applied to an @State property, $ provides a Binding to that state. This binding can then be passed to another view.</p><p>For example, a child view can declare a binding like this:</p><pre>struct PlayButton: View {<br>    @Binding var isPlaying: Bool<br><br>    var body: some View {<br>        Button(isPlaying ? &quot;Pause&quot; : &quot;Play&quot;) {<br>            isPlaying.toggle()<br>        }<br>    }<br>}</pre><p>Here PlayButton receives access to isPlaying, not ownership of its storage.</p><h4>Why Is a Binding a Reference, Not a Copy?</h4><p>Consider passing a plain Bool value to another view. The receiving view gets the value itself. Changing its local copy does not automatically update the original value.</p><p>A Binding, on the other hand, provides a connection to the existing source of truth. Reads access the current value, and writes are forwarded to its underlying storage.</p><ul><li><strong>Plain value:</strong> Passes the value itself.</li><li><strong>Binding:</strong> Passes a connection that forwards reads and writes to the original storage.</li></ul><p>This setup allows multiple views to work with the same state without maintaining independent copies.</p><h3>How @State and @Binding Work Together</h3><p>Now that we’ve looked at ownership and access separately, let’s connect the two in a complete parent-child example.</p><p>Consider a player interface where the parent manages the playback state and a child view provides the button to control it.</p><pre>// Parent View<br>struct PlayerView: View {<br>    @State private var isPlaying = false<br><br>    var body: some View {<br>        PlayButton(isPlaying: $isPlaying)<br>    }<br>}<br><br>// Child View<br>struct PlayButton: View {<br>    @Binding var isPlaying: Bool<br><br>    var body: some View {<br>        Button(isPlaying ? &quot;Pause&quot; : &quot;Play&quot;) {<br>            isPlaying.toggle()<br>        }<br>    }<br>}</pre><p>The connection between these views works through the projected value of @State.</p><p>Let’s trace the interaction:</p><ol><li><strong>Parent owns the state:</strong> PlayerView declares @State private var isPlaying = false.</li><li><strong>Parent passes a binding:</strong> It passes $isPlaying to PlayButton.</li><li><strong>Child receives the binding:</strong> PlayButton declares @Binding var isPlaying: Bool.</li><li><strong>Child modifies the value:</strong> Calling isPlaying.toggle() writes through the binding to the parent’s state.</li><li><strong>SwiftUI updates the interface:</strong> The state change invalidates the relevant view dependencies, and SwiftUI updates the affected parts of the interface.</li></ol><p>The child can now control the playback state without maintaining its own copy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHYOWelR9zZC95cdFWlD4g.png" /></figure><p><strong>@State owns the value. @Binding provides access to it.</strong></p><p>A binding allows another view to read and modify existing state without becoming another owner. This separation keeps a single source of truth and makes SwiftUI parent-child communication predictable.</p><p>Well, we will explore some more interesting things in upcoming posts, Utill then, Ciao and keep SwiftUI~ing!!! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b68b5aeb1b8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why onAppear Is Not a One-Time Lifecycle Event]]></title>
            <link>https://medium.com/cross-commit/why-onappear-is-not-a-one-time-lifecycle-event-38ea09da761f?source=rss-a769be0a8ae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/38ea09da761f</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swiftui-views]]></category>
            <category><![CDATA[swiftui-performance]]></category>
            <category><![CDATA[swiftui-onappear]]></category>
            <dc:creator><![CDATA[Rajveer]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 10:21:59 GMT</pubDate>
            <atom:updated>2026-10-21T22:12:31.839Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qqfvo-o7bc1Eo4BFX4LbRw.png" /></figure><p>Developers often assume that SwiftUI’s onAppear executes only once when a view is created. I was there once too, placing viewDidLoad related code in onAppear. However, Apple’s documentation makes no such guarantee.</p><p>Apple states that the exact moment SwiftUI calls <em>onAppear(perform:)</em> depends on the specific view type, although its action closure completes before the first rendered frame appears. The behaviour can also depend on structural identity. So, let’s talk about it a little more.</p><h3>The Misconception: onAppear Means “Initialize Once”</h3><p>Developers often treat onAppear as a one-time initialization hook, similar to viewDidLoad() in UIKit. However, onAppear and onDisappear are closer to UIKit’s viewDidAppear() and viewDidDisappear(), they are presentation-related callbacks, not initialization hooks.</p><p>Apple Developer Forums also highlight an important distinction: these callbacks relate to the view lifecycle, not necessarily to whether the view is visibly presented to the user.</p><p>Identity adds another layer of complexity. onAppear can execute in situations involving a new view identity, even when developers perceive the view as continuing from its previous state.</p><h3>SwiftUI Does Not Have a Direct viewDidLoad Equivalent</h3><p>SwiftUI does not provide a direct equivalent of UIKit’s viewDidLoad(). Apple’s documentation describes onAppear in terms of appearance and the timing of its action closure, not initialization or guaranteed one-time execution.</p><p>Instead, onAppear and onDisappear are closer to UIKit’s viewDidAppear() and viewDidDisappear(). They serve different purposes from viewDidLoad() and should not be treated as interchangeable lifecycle events.</p><p>This distinction becomes clearer when we consider SwiftUI’s value-based view model. SwiftUI views are commonly structs, and creating a new view value does not necessarily mean creating a new logical UI element.</p><p>As Apple’s WWDC21 session Demystify SwiftUI explains, views sharing the same identity represent different states of the same conceptual UI element.</p><h3>Four Events Developers Confuse with onAppear</h3><h4>View Value Creation</h4><p>SwiftUI views are value types, typically defined as structs. Every view instance has a value.</p><p>When a parent’s body is reevaluated, SwiftUI can create new view struct values. Consequently, a view’s init may execute repeatedly, even when the logical UI element remains the same.</p><p>Any work performed directly in init, such as network calls, database queries, or expensive computations can therefore run more often than expected.</p><p>Creating a new view value does not necessarily mean creating a new logical view or resetting its state.</p><h4>Body Reevaluation</h4><p>SwiftUI views are a function of state. When state changes, SwiftUI reevaluates the relevant parts of the view hierarchy to reflect the new values.</p><p>This does not mean onAppear executes again every time body is reevaluated. Body reevaluation and appearance callbacks represent different events.</p><p>The body property is computed, and SwiftUI can evaluate it repeatedly as state and rendering requirements change. It should remain a lightweight description of the interface rather than a place for side effects or state initialization that triggers further updates.</p><p>A state change can cause body reevaluation without causing another onAppear callback.</p><h4>Disappearance and Reappearance</h4><p>A view can disappear from the hierarchy and appear again, causing onAppear to execute more than once.</p><p>For example, views inside a LazyVStack can trigger onAppear repeatedly as they enter the viewport during scrolling.</p><p>These callbacks are not limited to the first appearance during an app session. They can occur again when a view re-enters the relevant hierarchy or appears again within its container.</p><p>Reappearance can trigger onAppear again, even when the developer considers the screen to be the same logical screen.</p><h4>Identity Replacement</h4><p>SwiftUI uses identity to determine whether successive view values represent the same logical UI element. Changing that identity can reset the view’s associated state.</p><p>Apple’s documentation for id(_:) explicitly states that when the supplied ID changes, the view’s identity and associated state is reset.</p><pre>struct ContentView: View {<br>    @State private var viewID = UUID()<br><br>    var body: some View {<br>        DetailView()<br>            .id(viewID)<br>    }<br>}</pre><p>When viewID changes, SwiftUI treats DetailView as a different logical view. Its previous state is no longer preserved under the new identity, and appearance-related work can run again as the replacement enters the hierarchy.</p><p>Identity replacement is not merely another body reevaluation. It can establish a new state lifetime, which affects @State, onAppear, and .task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e66wErPEnJsxeQUwI1X4Ng.png" /></figure><h3>Why This Matters for API Calls</h3><p>Starting asynchronous work inside onAppear using Task { } does not automatically tie that task’s lifetime to the view. If the view disappears before the work completes, the task can continue running, potentially wasting resources or updating stale state.</p><p>The .task modifier is designed for this scenario. It associates asynchronous work with the view’s lifetime, allowing SwiftUI to cancel the task when the view disappears. Meanwhile, .task(id:) also cancels and restarts the task when its identifier changes.</p><p>However, .task is not a guaranteed one-time execution mechanism. Its behavior depends on view lifetime and task identity, and cancellation is cooperative but not a guarantee that every underlying operation stops immediately.</p><p>Prefer .task for view-scoped asynchronous work, and use explicit cancellation or request deduplication when the operation requires stronger guarantees.</p><h3>When Should You Use onAppear?</h3><h4>Good Uses</h4><ul><li>Analytics tracking: Firebase Analytics and Matomo support logging screen-view events from onAppear in SwiftUI.</li><li>Appearance-dependent actions: Use it for lightweight actions that should occur when a view appears, rather than for one-time initialization.</li></ul><h4>Use With Caution</h4><ul><li>One-time initialization: onAppear can execute more than once, so it is not a reliable one-time setup mechanism.</li><li>API calls and side effects: Avoid placing them directly in body, where reevaluation can trigger repeated work. Use .task, onAppear, or onChange according to the intended trigger and task lifetime.</li><li>TabView child views: Some configurations, including reported cases involving PageTabViewStyle, have triggered excessive appearance callbacks. Where behavior is unreliable, track the relevant state explicitly and consider .onChange or debouncing.</li></ul><p>Choose the callback based on when the action should happen, not on the assumption that it will execute only once.</p><p>Apple’s documentation does not guarantee that onAppear executes only once, nor does it describe it as an equivalent to UIKit’s viewDidLoad(). Its behavior depends on the view’s lifecycle and identity.</p><p>The right approach is to choose the abstraction based on the intended lifetime of the work:</p><ul><li>Appearance-related actions: onAppear</li><li>Asynchronous work tied to view lifetime: .task</li><li>Data requiring caching or request deduplication: A model, repository, or caching layer</li></ul><p>And that’s a wrap for today! Until next time, keep exploring SwiftUI. See you in the next blog post. Ciao! 💙</p><h3>Thanks for reading Cross Commit</h3><p>Before you go:</p><figure><img alt="Follow Cross Commit: practical Swift, Kotlin and mobile AI stories from engineers who ship real apps" src="https://cdn-images-1.medium.com/max/1024/1*aojKTaZmGnisRaGyAL1g0g.png" /><figcaption>Follow Cross Commit on Medium: <a href="https://medium.com/cross-commit">medium.com/cross-commit</a></figcaption></figure><p>👉 <strong>Clap</strong> and <strong>follow</strong> <a href="https://medium.com/u/a769be0a8ae0">Rajveer</a> so their next story lands in your feed 👏</p><p>👉 Want their stories by email? After you follow, tap <strong>Following</strong> on their profile and choose <strong>Email notifications on</strong> 📩</p><p>👉 <strong>Follow </strong><a href="https://medium.com/cross-commit"><strong>Cross Commit</strong></a> for practical iOS, Android and mobile AI stories from engineers who ship real apps</p><p>👉 Writing about Swift, Kotlin or mobile AI? Cross Commit is open to writers worldwide. Leave a response below and we’ll get in touch ✍️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38ea09da761f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cross-commit/why-onappear-is-not-a-one-time-lifecycle-event-38ea09da761f">Why onAppear Is Not a One-Time Lifecycle Event</a> was originally published in <a href="https://medium.com/cross-commit">Cross Commit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI State Storage: Where Does @State Actually Live?]]></title>
            <link>https://medium.com/@raajveer/swiftui-state-storage-where-does-state-actually-live-0b38dac8cea4?source=rss-a769be0a8ae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b38dac8cea4</guid>
            <category><![CDATA[swiftui-views]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swiftui-state]]></category>
            <category><![CDATA[swiftui-performance]]></category>
            <dc:creator><![CDATA[Rajveer]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 09:15:58 GMT</pubDate>
            <atom:updated>2026-10-12T09:15:58.585Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZ3NaXc2ifBXVwNIPwbBDA.png" /></figure><p>SwiftUI views are value types (structs), and SwiftUI recreates them frequently. Each time SwiftUI evaluates a view’s body, it produces a new view description. Yet, despite these repeated recreations, a @State property retains its value. If @State lived directly inside the struct, its value would reset to its initial default whenever a new instance was created.</p><p>Consider this simple example:</p><pre>struct CounterView: View {<br>    @State private var count = 0<br><br>    var body: some View {<br>        Button(&quot;Count: \(count)&quot;) {<br>            count += 1<br>        }<br>    }<br>}</pre><p>Even when SwiftUI recreates CounterView, count retains its updated value. This raises a question: <strong>if the view struct is recreated, where does the state actually live?</strong></p><p>This article explores the storage mechanics of @State where its value lives, how SwiftUI associates it with a view, and when that storage is destroyed.</p><blockquote>@State <strong>does not store its persistent value directly in the view struct.</strong> Instead, it provides access to SwiftUI-managed storage associated with the view’s identity.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZjr-h0CrTQRHE-n9LsfKg.png" /></figure><h4>Views Are Blueprints, Not Storage Containers</h4><p>A SwiftUI view is a lightweight description of the UI, not a permanent container for its data. Whenever SwiftUI needs to update the interface, it evaluates the view’s body and works with the resulting view description. The view struct itself can be recreated, so its stored properties aren’t a reliable place for values that must persist across renders.</p><p>As in the above CounterView example, count belongs directly to the struct. Creating a new CounterView instance initializes it to 0 again. A value that must survive view recreation needs a different storage mechanism.</p><p>This is where @State comes in. Apple’s documentation describes it as “a property wrapper type that can read and write a value managed by SwiftUI” and explains that “SwiftUI manages the property’s storage.”</p><p>In other words, the view struct provides access to the value, but SwiftUI manages its persistent storage.</p><h4>@State as a Storage Redirect</h4><p>@State acts as a bridge between the view struct and storage managed by SwiftUI. Rather than keeping the persistent value inside the struct, the property wrapper provides access to that external storage.</p><p>Consider this declaration:</p><p>@State private var isPlaying: Bool = false</p><p>Here, <em>false</em> is the initial value SwiftUI uses when setting up storage for this state property. Once the storage is established, subsequent view recreations can access the existing value instead of resetting it to false.</p><p>Apple’s documentation explains why state should be private:</p><blockquote>“Declare state as private to prevent setting it in a memberwise initializer, which can conflict with the storage management that SwiftUI provides.”</blockquote><p>The reason is that SwiftUI manages the lifetime and initialization of the underlying storage. Exposing the property through a memberwise initializer can interfere with that management.</p><p>The @State property wrapper gives the view a <strong>wrapped value</strong> to read and write, while the persistent value lives in storage managed by SwiftUI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stoiBRWFZTxP_wV8Woyp_g.png" /></figure><h3>SwiftUI’s Internal Storage Model</h3><p>SwiftUI maintains internal storage for state owned by views. When a view first appears, SwiftUI establishes storage for its @State properties. That storage is associated with the view’s identity, allowing the values to persist even when the view struct is recreated.</p><p>The basic read and write flows look like this:</p><ul><li><strong>Read</strong>: The view struct accesses the property wrapper, which retrieves the value from the storage cell.</li><li><strong>Write</strong>: The property wrapper updates the storage cell, triggering SwiftUI to update the relevant view.</li></ul><p>When you mutate a @State property, the new value is written to SwiftUI-managed storage. Because the view’s body depends on that state, SwiftUI updates the affected parts of the view hierarchy. See here:</p><pre>@State private var count = 0<br><br>var body: some View {<br>    Button(&quot;Count: \(count)&quot;) {<br>        count += 1<br>    }<br>}</pre><p>When the button is tapped, count changes. SwiftUI then reevaluates the relevant view description, creating a new view struct as needed. The updated value is available from the existing state storage when the new body is evaluated.</p><p>Apple’s documentation summarises this behavior:</p><blockquote>“SwiftUI manages the property’s storage. When the value changes, SwiftUI updates the parts of the view hierarchy that depend on the value.”</blockquote><p>C<strong>hanging state triggers a UI update, but it doesn’t require the state storage itself to be recreated.</strong> SwiftUI can rebuild view descriptions while preserving the state associated with their identity.</p><h3>Identity Is the Storage Key</h3><p>SwiftUI uses a view’s <strong>identity</strong> to determine whether its existing state storage should be reused. When identity remains stable, the associated storage cell persists, even if SwiftUI creates a new instance of the view struct.</p><p>SwiftUI identifies views in two ways:</p><ul><li><strong>Structural identity:</strong> The default mechanism. SwiftUI identifies a view based on its position and structure within the view hierarchy. When the structure remains consistent, SwiftUI can recognize the view across updates.</li><li><strong>Explicit identity:</strong> The .id() modifier lets you associate a view’s identity with a specific value. When that value changes, SwiftUI treats the view as having a new identity, resetting its associated state.</li></ul><p>For example in our CounterView example, changing this value changes CounterView’s identity.</p><pre>CounterView()<br>      .id(userID)</pre><p>As long as userID remains unchanged, SwiftUI can preserve the state associated with that identity. When userID changes, the view receives a new identity, and its state is initialized again.</p><p><strong>Identity is not the same as the struct instance.</strong> Apple’s <em>SwiftUI foundations</em> video explains:</p><blockquote>“State properties match the lifetime of the view in the interface, not the lifetime of the view struct itself. This storage is indexed by the view’s identity.”</blockquote><p>The struct can be recreated many times, but its state storage persists as long as SwiftUI recognizes the view as having the same identity. State is lost when its associated identity’s lifetime ends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-JGdq6M3LW7pVPNvzRBVsg.png" /></figure><h4>State Lifetime Follows Identity Lifetime</h4><p>The lifetime of @State storage follows the lifetime of the view’s identity, not the lifetime of its struct instance.</p><p>The lifecycle is straightforward:</p><ol><li><strong>Identity is created: </strong>SwiftUI allocates storage and initializes the state.</li><li><strong>Identity remains stable: </strong>Storage persists across multiple body evaluations.</li><li><strong>Identity is destroyed: </strong>Its associated storage is released, and the state is lost.</li><li><strong>A new identity is created: </strong>SwiftUI allocates new storage and initializes the state again.</li></ol><p>The WWDC21 session <em>Demystify SwiftUI</em> explains:</p><blockquote>“Whenever the identity changes, the state is replaced. The persistence of your state is tied to the lifetime of your views.”</blockquote><p>Apple’s <em>SwiftUI foundations</em> video illustrates this with navigation:</p><blockquote>“When someone navigates away from this view, SwiftUI deletes the entry from its storage. If they come back to the view later, SwiftUI assigns a new identity and allocates a new entry in its storage.”</blockquote><p>This explains why navigating away from a view and later returning to it can reset its @State properties. If the original identity no longer exists, SwiftUI no longer has that identity’s state storage to restore.</p><h3>View Recreation vs State Recreation</h3><p>As we know that SwiftUI frequently creates new view structs to reflect UI updates, but that doesn’t mean it recreates their state. As long as the view’s identity remains stable, the existing state storage persists.</p><p>As the WWDC session <em>Demystify SwiftUI</em> explains:</p><blockquote>“View values are ephemeral and you should not rely on their lifetime. But their identity is not, and is what gives them continuity.”</blockquote><p>This is why @State works despite SwiftUI’s use of value types. <strong>The view struct is temporary; the state storage persists for the lifetime of its identity.</strong></p><h3>When Identity Changes: Storage Deallocation Cases</h3><p>So, given that when a view’s identity changes, SwiftUI can discard its existing state storage and create new storage with the initial values. This commonly happens in four situations.</p><h4>If/else branches</h4><p>Different branches of an if/else conditional have different structural identities. Switching branches changes which view exists at that position in the hierarchy.</p><p>As <em>Demystify SwiftUI</em> explains:</p><blockquote>“It creates new storage for the false view, starting with the state’s initial value, and the storage for the true view is deallocated right after. But what if we go back to the true branch? Well, that’s a new view again, so SwiftUI creates new storage, starting again from the state’s initial value.”</blockquote><p>When a branch disappears, its associated state storage can be released. Returning to that branch creates a new view identity with a freshly initialized state.</p><h4>.id() value changes</h4><p>The .id() modifier explicitly ties a view’s identity to a value. Apple’s documentation for id(_:) states:</p><blockquote>“When the proxy value specified by the id parameter changes, the identity of the view,for example, its state is reset.”</blockquote><pre>PlayerView()<br>   .id(selectedTrackID)</pre><p>When selectedTrackID changes, SwiftUI resets the view’s identity and associated state. Its @State properties are initialized again for the new identity.</p><h4>ForEach with unstable IDs</h4><p>In ForEach, SwiftUI uses the identity of the supplied data to determine which views correspond to which elements. As <em>Demystify SwiftUI</em> explains:</p><blockquote>“Choosing a good identifier is your opportunity to control the lifetime of your views and data.”</blockquote><p>Unstable identifiers can make SwiftUI interpret existing elements as new ones, causing views to be recreated rather than updated. This can discard their @State and animation context.</p><p>Prefer stable identifiers tied to the underlying data:</p><pre>ForEach(tasks) { task in<br>     TaskRow(task: task)<br>}</pre><p>Here, Task should provide a stable Identifiable identity. Avoid relying on array indices when elements can be inserted, removed, or reordered, because an index identifies a position rather than a particular element.</p><h4>The .id(UUID()) anti-pattern</h4><p>Consider this example:</p><pre>PlayerView()<br>    .id(UUID())</pre><p>Every time this expression is reevaluated, UUID() generates a new value. SwiftUI therefore sees a different identity and resets the view’s associated state.</p><p>If this happens repeatedly, the view can continually lose its @State values instead of preserving them across updates.</p><p><strong>Notice one thing is the same in every case:</strong> when SwiftUI sees a new identity, it treats the view as a new lifetime, with new state storage. Stable identity allows the state to persist; unstable identity can repeatedly destroy that continuity.</p><h3>Dynamic Properties and Storage Injection</h3><p>@State participates in SwiftUI’s <strong>dynamic property system</strong>. Before evaluating a view’s body, SwiftUI updates its dynamic properties so they can access the appropriate state storage.</p><p>This explains why the property’s initializer is not the source of truth after the initial storage setup. The initializer provides the starting value, while subsequent evaluations access the value associated with the view’s identity.</p><pre>struct PlayerView: View {<br>    @State private var isPlaying = false<br><br>    var body: some View {<br>        Text(isPlaying ? &quot;Playing&quot; : &quot;Paused&quot;)<br>    }<br>}</pre><p>When SwiftUI establishes storage for this state property, false provides the initial value. On subsequent updates, the property wrapper accesses the existing storage rather than resetting the value to false.</p><p>At an implementation level, SwiftUI must discover a view’s dynamic properties and connect them to the appropriate storage. One explanation of this mechanism involves Swift’s reflection capabilities: inspecting stored-property metadata to identify properties that conform to DynamicProperty, then associating them with the relevant storage locations.</p><p>For instance, the State&lt;Int&gt; backing an integer state property needs access to the storage associated with that property’s view identity. SwiftUI’s internal implementation details are not fully public, so the exact discovery and injection mechanism should not be treated as a guaranteed implementation contract.</p><p>The important thing is that <strong>property initialization and state storage are separate operations</strong>. The initializer supplies the starting value when storage is established for an identity; the dynamic property system enables the view to access that storage during subsequent body evaluations.</p><h3>The @State Macro: Lazy Initialization</h3><p>At WWDC 2026, Apple announced a significant change to @State: it has been rewritten as a Swift macro. This changes how initial values are evaluated, particularly when a state property stores a reference type such as a class.</p><p>Previously, initializing a reference-type value inline could create a new object every time SwiftUI recreated the view struct, even when the view’s identity remained unchanged. SwiftUI would continue using the existing state storage, leaving the newly created object unused. The result was unnecessary object creation.</p><p>With the @State macro in Xcode 27, the initial value can be evaluated lazily, avoiding repeated initialization when the existing storage is already available.</p><p>Apple’s WWDC26 session <em>What’s new in SwiftUI</em> explains:</p><blockquote>“In the 2027 releases, for the first time, classes initialized and stored using State properties are now lazy, which means they will only be initialized once. This is thanks to the conversion of State from a Dynamic Property to a macro!”</blockquote><p>This behaviour has also been back-ported to releases where @Observable was first introduced, starting with iOS 17.</p><p>Technical Note TN3211 confirms the underlying change:</p><blockquote>“State is a Swift macro rather than a property wrapper. The macro enables lazy evaluation of a property’s initial value, and the compiler treats the property like any other stored property of the view.”</blockquote><p>This change can introduce source-breaking differences in existing code. For example, code that assigns a value to a @State property inside init after declaring its default value may now fail to compile because the property is used before initialization.</p><p>Consider this example:</p><pre>struct PlayerView: View {<br>    @State private var model = PlayerModel()<br><br>    init() {<br>        // Assigning to model here may fail to compile<br>        // under the macro&#39;s initialization rules.<br>    }<br><br>    var body: some View {<br>        Text(&quot;Player&quot;)<br>    }<br>}</pre><p>V<strong>iew initialization and state initialization are not the same thing</strong>. SwiftUI can recreate the view struct many times while retaining the same state storage. Lazy initialization helps prevent unnecessary creation of reference-type values when that storage already exists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3Pp4n7OeQ8YSczdRc9cAQ.png" /></figure><p>And that’s a wrap! 🎉 Now you know where @State actually lives and why view identity matters. See you in the next blog with another interesting SwiftUI concept. Until then, happy SwiftUI!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b38dac8cea4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI AnyView, Navigation, and Rendering: Advanced View Tree Guide]]></title>
            <link>https://medium.com/cross-commit/swiftui-anyview-navigation-and-rendering-advanced-view-tree-guide-7bcfe1e9cb62?source=rss-a769be0a8ae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bcfe1e9cb62</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swiftui-view-tree]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swiftui-performance]]></category>
            <category><![CDATA[swiftui-rendering]]></category>
            <dc:creator><![CDATA[Rajveer]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 10:57:29 GMT</pubDate>
            <atom:updated>2026-10-21T03:30:18.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ds19GYuPfcT5Lz3Y4qITRA.png" /></figure><p>So far, we’ve explored how <strong>view identity and state lifetime</strong> works in <a href="https://medium.com/@raajveer/swiftui-view-tree-explained-view-identity-and-structural-identity-8aa9ada8dc9e">part 1</a> and <a href="https://medium.com/@raajveer/swiftui-state-lifetime-and-identity-conditional-branches-and-id-explained-4373b6d59b5b">part 2</a>. Identity becomes even more interesting when we look at how SwiftUI handles <strong>type erasure, navigation, and rendering</strong>.</p><p>In this part, we’ll see how AnyView can hide view structure, how <strong>navigation identity</strong> affects destination state, and how SwiftUI turns view descriptions into the UI we actually see. Together, these concepts complete the picture of how SwiftUI understands, updates, and renders its View Tree.</p><h3>AnyView</h3><p>AnyView is SwiftUI’s <strong>type erased wrapper</strong>. It hides the concrete type of the view it wraps and exposes only AnyView to the surrounding hierarchy.</p><p>SwiftUI’s rendering system relies heavily on <strong>type information and structural identity</strong> to understand how a view hierarchy has changed. When you erase that information, you remove signals that SwiftUI can otherwise use to efficiently reconcile the hierarchy.</p><p>For example:</p><pre>@ViewBuilder<br>func content(for state: State) -&gt; some View {<br>    if state.isLoading {<br>        ProgressView()<br>    } else {<br>        ContentView()<br>    }<br>}</pre><p>The compiler preserves the underlying structure of these different branches. If you instead force both paths through AnyView, that structural information is hidden:</p><pre>// Type information is erased<br>func content(for state: State) -&gt; AnyView {<br>    if state.isLoading {<br>        return AnyView(ProgressView())<br>    } else {<br>        return AnyView(ContentView())<br>    }<br>}</pre><h4>Why Type Erasure Can Hurt</h4><p>SwiftUI can use concrete view types as part of its <strong>diffing algorithm</strong>. Type erasure makes that information less available, potentially requiring SwiftUI to do more work when reconciling changes. It also weakens the compiler’s ability to reason about the hierarchy and perform <strong>compile-time optimizations</strong>.</p><p>Most importantly, AnyView should not be thought of as a substitute for identity. Multiple views wrapped in AnyView all present the same erased outer type, so you lose useful structural information that would otherwise distinguish their concrete view types.</p><p>This is particularly relevant in dynamic hierarchies such as lists and ForEach, where SwiftUI needs reliable information to efficiently determine which elements changed.</p><p>Apple called this out explicitly in its WWDC21 guidance:</p><blockquote><strong>“AnyView makes it hard for SwiftUI to optimize and identify each view, avoid it as much as possible.”</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jK2_JmyZUeP-4jnXyDBo-g.png" /></figure><h4>Prefer Preserving Type Information</h4><p>In most cases, SwiftUI provides alternatives that avoid unnecessary type erasure.</p><p><strong><em>@ViewBuilder</em> </strong>lets multiple conditional branches coexist while preserving their underlying type structure:</p><pre>@ViewBuilder<br>var content: some View {<br>    if isLoading {<br>        ProgressView()<br>    } else {<br>        ContentView()<br>    }<br>}</pre><p><strong><em>some View</em></strong> keeps the concrete return type opaque to the caller while allowing the compiler to know what that type actually is:</p><pre>func makeContent() -&gt; some View {<br>    VStack {<br>        Text(&quot;Hello&quot;)<br>        Image(systemName: &quot;star&quot;)<br>    }<br>}</pre><p>And <strong><em>Group</em></strong> can be used to organize views without introducing type erasure:</p><pre>Group {<br>    Text(&quot;Title&quot;)<br>    Text(&quot;Subtitle&quot;)<br>}</pre><p><em>some View</em> is <strong>opaque typing</strong>, while <em>AnyView</em> is <strong>type erasure</strong>. With <em>some View</em>, the compiler still knows the underlying concrete type. With <em>AnyView</em>, that information has deliberately been erased.</p><h4>When AnyView Is Fine</h4><p><em>AnyView</em> can be reasonable when you genuinely need <strong>runtime type erasure</strong>, particularly for a single view used once, during prototyping, or when bridging APIs that require a type-erased view, for example, when integrating with UIKit hosting infrastructure.</p><blockquote><strong>Don’t reach for AnyView just because two branches return different view types. Let @ViewBuilder and some View preserve the type information whenever possible.</strong></blockquote><h3>Navigation</h3><p>Navigation in SwiftUI is deeply connected to identity. A navigation stack is not simply a sequence of screens, it is a sequence of <strong>identified navigation values</strong> that SwiftUI uses to determine which destinations should exist.</p><p>With NavigationStack, navigation state is represented by a path containing Hashable values:</p><pre>@State private var path: [Route] = []<br><br>NavigationStack(path: $path) {<br>    ContentView()<br>        .navigationDestination(for: Route.self) { route in<br>            DestinationView(route: route)<br>        }<br>}</pre><p>For example:</p><pre>enum Route: Hashable {<br>    case profile(Int)<br>    case settings<br>}</pre><p>When you append a route:</p><pre>path.append(.profile(42))</pre><p>SwiftUI resolves that value to the corresponding destination. The <strong>route value</strong> determines what belongs on the navigation stack, while the destination’s <strong>view identity</strong> determines the lifetime of its associated state.</p><h4>Route Identity vs. View Identity</h4><p>These are related, but they are not the same concept. <strong>Route identity controls navigation. </strong>It answers “Which destination should exist in the navigation stack?”. <strong>View identity controls state lifetime. </strong>It answers “Should this destination be treated as the same view as before?”. This becomes important when navigation values change.</p><p>Consider:</p><pre>enum Route: Hashable {<br>  case user(id: Int)<br>}</pre><p>If the path contains:</p><p>[.user(id: 1)]</p><p>and later becomes:</p><p>[.user(id: 2)]</p><p>the navigation route has changed. SwiftUI therefore resolves a different destination value, and the resulting destination may receive a different identity and state lifetime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cvmz9LF_d3VgSIf3h96ZJw.png" /></figure><h4>State While a View Is on the Navigation Stack</h4><p>A destination pushed onto a navigation stack is not equivalent to simply removing the previous view from the hierarchy. The navigation stack maintains the pushed route as part of its navigation state, allowing the destination and its associated state to remain logically alive while the user navigates deeper. For example:</p><pre>struct DetailView: View {<br>    @State private var count = 0<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Count: \(count)&quot;)<br><br>            Button(&quot;Increment&quot;) {<br>                count += 1<br>            }<br>        }<br>    }<br>}</pre><p>If DetailView is pushed and the user navigates to another destination, returning to it can preserve its state because the original navigation route remains part of the stack. Popping the destination is different:</p><p>path.removeLast()</p><p>The route is removed from the navigation path. Conceptually, the corresponding destination leaves the active navigation hierarchy, and its view-local state can be discarded.</p><p>If the same route is pushed again later, SwiftUI can create a new destination identity, so the view starts with fresh state.</p><p>This follows the same identity principle we saw earlier. With stable identity, SwiftUI treats the view as the same conceptual view, allowing its state to be preserved. When that identity is removed or replaced, SwiftUI sees a new conceptual view, and its state begins a new lifetime.</p><h4>Prefer Value-Based Navigation</h4><p>For predictable identity and state behaviour, modern SwiftUI navigation is generally easier to reason about when navigation is driven by values:</p><pre>NavigationStack(path: $path) {<br>    HomeView()<br>        .navigationDestination(for: Route.self) { route in<br>            switch route {<br>            case .profile(let id):<br>                ProfileView(userID: id)<br><br>            case .settings:<br>                SettingsView()<br>            }<br>        }<br>}</pre><p>Here, the route itself becomes the source of truth for navigation. SwiftUI can compare the values in the path and determine which destinations need to be inserted, removed, or updated.</p><p>This is often more predictable than older patterns that drive navigation through conditional NavigationLink(isActive:) state, particularly when the navigation hierarchy becomes complex and destination state needs to survive navigation changes.</p><h4>A Lazy Container</h4><p>There is an important caveat when discussing state and identity: <strong>identity alone does not guarantee that every piece of view-local state will remain alive indefinitely.</strong></p><p>Lazy containers such as LazyVStack and List can create and discard views as they move into and out of the visible region. This is an intentional optimisation.</p><pre>ScrollView {<br>    LazyVStack {<br>        ForEach(items) { item in<br>            ItemRow(item: item)<br>        }<br>    }<br>}</pre><p>Even when an item has a stable identity, its view representation may not remain instantiated while it is off-screen. State behavior in lazy containers can therefore differ from the mental model of a permanently instantiated view, and certain kinds of view-local state may appear to reset depending on how the hierarchy is structured.</p><blockquote><strong>Identity answers which view an element represents; it does not promise that the view’s concrete representation is continuously instantiated.</strong></blockquote><p>For data-driven lists, keep identity stable and move important persistent data into an appropriate model or source of truth rather than relying on the lifetime of an individual row view.</p><p>Navigation follows the same fundamental identity rule we have seen throughout this article. The navigation path determines the route identity, which determines the destination and, ultimately, the view identity and its state lifetime. Once navigation is understood in terms of identity rather than simply screens being pushed and popped, state preservation becomes much easier to reason about.</p><blockquote><strong>Use stable, value-based routes for navigation, give data-driven destinations stable identities, and avoid depending on view-local state for data that must survive beyond the lifetime of the destination view.</strong></blockquote><h3>Rendering</h3><p>So far, we have looked at <strong>identity</strong> and <strong>state lifetime</strong>. Now we can connect those concepts to what happens when SwiftUI actually updates the UI.</p><p>The idea is simple: when state changes, SwiftUI evaluates the relevant parts of the view hierarchy again and produces a new description of the UI. It then compares that description with the previous one to determine what has changed. In other words, a SwiftUI view is best understood as a function of its inputs:</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><br>            Button(&quot;Increment&quot;) {<br>                count += 1<br>            }<br>        }<br>    }<br>}</pre><p>When count changes, SwiftUI does not treat the entire application as something that must be recreated from scratch. The affected part of the hierarchy is evaluated again, producing a new view description.</p><h4>AttributeGraph and Dependency Tracking</h4><p>Underneath SwiftUI’s declarative API is an internal dependency system commonly associated with <strong>AttributeGraph</strong>. It can be thought of as a directed acyclic graph (DAG) of values and dependencies rather than simply a tree of views.</p><p>When a value changes, SwiftUI can use these dependency relationships to determine which computations have been invalidated and need to be reconsidered. For example, app state may be consumed by the header and content, while the content also drives the list. This dependency structure helps SwiftUI identify the parts of the hierarchy that need to be reevaluated.</p><p>A change to state does not necessarily mean every node must be recomputed. SwiftUI uses the dependency information available to it to limit the amount of work required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1fYXTFOcGEdhy3fgh9oUg.png" /></figure><p>AttributeGraph itself is a private implementation detail, so its exact behavior and internal representation can change between OS releases. The useful mental model is that SwiftUI maintains dependency information that helps drive invalidation and re-computation.</p><h4>Stable Identity vs. Changed Identity</h4><p>This is where everything from the previous sections comes together. When SwiftUI encounters a view with stable identity, it can associate the newly evaluated description with the existing conceptual view, allowing its state storage to continue across updates. For example, a CounterView whose count changes from 5 to 6 retains the same identity, so SwiftUI updates the relevant UI while preserving its state and allowing animations to interpolate between the old and new values.</p><p>When the identity changes, SwiftUI treats the new view as a different conceptual element. The previous identity and its associated state can leave the hierarchy, while the new identity enters with its own state storage. As a result, the old state may be discarded and recreated, and insertion or removal transitions can participate in the update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UIiNgTko8tLjhvgOW8C0Ow.png" /></figure><p>This is why a tiny-looking code change such as moving a view between conditional branches or changing an explicit .id(), can have consequences far beyond the line that changed.</p><h4>The View Tree Is Not the Render Tree</h4><p>The <strong>View Tree</strong> is the declarative structure produced by your SwiftUI code. It describes what the UI should represent.</p><p>The <strong>render tree</strong>, however, is the structure SwiftUI ultimately uses to perform layout, drawing, interaction, and other rendering work.</p><p>These two structures do not have to be identical. For example:</p><pre>Group {<br>    Text(&quot;Hello&quot;)<br>    Image(systemName: &quot;star&quot;)<br>}</pre><p>Group is primarily a structural container. It does not necessarily correspond to a standalone rendered element.</p><p>Similarly, ForEach provides data-driven structure and identity to a collection of views, but SwiftUI is free to represent that structure differently internally when constructing the final rendering representation.</p><p>SwiftUI can therefore <strong>flatten, combine, optimize, or otherwise transform portions of the declarative hierarchy</strong> when building the structures required for rendering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZR8_7n_ZN2ENHeE-U67cg.png" /></figure><h4>Why Identity and Type Erasure Affect Performance</h4><p>SwiftUI’s ability to efficiently reconcile updates depends on the information available to it. Stable identity gives SwiftUI a reliable answer to: “Is this the same conceptual element as before?”.</p><p>Concrete view types provide another important part of the structural information available during reconciliation. This is why the patterns discussed earlier can affect performance. With stable structure:</p><pre>ForEach(items) { item in<br> ItemRow(item: item)<br>}</pre><p>SwiftUI has useful information about the structure and identity of each element. With unstable identity:</p><pre>// Identity changes every evaluation<br>ItemRow(item: item)<br>   .id(UUID())</pre><p>SwiftUI is repeatedly being told that the view is a different identity, which can prevent effective state reuse and cause unnecessary lifecycle work.</p><p>Likewise, excessive AnyView removes concrete type information that SwiftUI can otherwise use when reasoning about the view hierarchy.</p><pre>// Unnecessary type erasure<br>AnyView(<br>  ItemRow(item: item)<br>)</pre><p>Neither AnyView nor .id() is inherently “slow.” The problem is <strong>using them in ways that discard information SwiftUI could otherwise use for efficient reconciliation</strong>.</p><blockquote><strong>Give SwiftUI stable identity and as much useful structural information as possible.</strong></blockquote><p>That allows the framework to do what its declarative model is designed for: determine what actually changed and minimize the work required to reflect that change on screen.</p><p><strong>Think of rendering as a pipeline that begins with a state change, followed by dependency invalidation, body evaluation, creation of a new view description, reconciliation, and finally the rendered update. Identity determines whether SwiftUI can connect that new description to what already existed, while the final render representation may differ substantially from the declarative View Tree you wrote.</strong></p><p>This brings us to the end of our journey through the <strong>SwiftUI View Tree</strong>.</p><p>We started with <strong>view identity and structural identity</strong>, then explored how they determine <strong>state lifetime</strong>, conditional branches, and the behavior of .id(). Finally, we looked at how AnyView, navigation, and rendering fit into it.</p><p><strong>SwiftUI is not just rebuilding views, it is continuously interpreting their structure and identity to determine what should persist, change, or disappear.</strong></p><p>So, we’ll meet again with something new. Until then, Happy SwiftUI! Ciao.</p><h3>Thanks for reading Cross Commit</h3><p>Before you go:</p><figure><img alt="Follow Cross Commit: practical Swift, Kotlin and mobile AI stories from engineers who ship real apps" src="https://cdn-images-1.medium.com/max/1024/1*aojKTaZmGnisRaGyAL1g0g.png" /><figcaption>Follow Cross Commit on Medium: <a href="https://medium.com/cross-commit">medium.com/cross-commit</a></figcaption></figure><p>👉 <strong>Clap</strong> and <strong>follow</strong> <a href="https://medium.com/u/a769be0a8ae0">Rajveer</a> so their next story lands in your feed 👏</p><p>👉 Want their stories by email? After you follow, tap <strong>Following</strong> on their profile and choose <strong>Email notifications on</strong> 📩</p><p>👉 <strong>Follow </strong><a href="https://medium.com/cross-commit"><strong>Cross Commit</strong></a> for practical iOS, Android and mobile AI stories from engineers who ship real apps</p><p>👉 Writing about Swift, Kotlin or mobile AI? Cross Commit is open to writers worldwide. Leave a response below and we’ll get in touch ✍️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bcfe1e9cb62" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cross-commit/swiftui-anyview-navigation-and-rendering-advanced-view-tree-guide-7bcfe1e9cb62">SwiftUI AnyView, Navigation, and Rendering: Advanced View Tree Guide</a> was originally published in <a href="https://medium.com/cross-commit">Cross Commit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI State Lifetime and Identity: Conditional Branches and .id() Explained]]></title>
            <link>https://medium.com/cross-commit/swiftui-state-lifetime-and-identity-conditional-branches-and-id-explained-4373b6d59b5b?source=rss-a769be0a8ae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4373b6d59b5b</guid>
            <category><![CDATA[swiftui-view-tree]]></category>
            <category><![CDATA[swiftui-views]]></category>
            <category><![CDATA[swiftui-performance]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Rajveer]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 10:55:55 GMT</pubDate>
            <atom:updated>2026-10-20T22:27:59.634Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qKG1bIajN6PrsC-JJmnUg.png" /></figure><p>In the <a href="https://medium.com/@raajveer/swiftui-view-tree-explained-view-identity-and-structural-identity-8aa9ada8dc9e">previous article</a>, we explored how <strong>SwiftUI’s View Tree and identity</strong> determine how views are understood across updates. The next question is: <strong>what happens to a view’s state when its identity changes?</strong></p><p>SwiftUI associates state with a view’s identity, which means that seemingly small structural changes can affect how long that state survives. <strong>Conditional branches</strong> can create different view identities, while .id() lets you explicitly define when SwiftUI should treat a view as a new identity.</p><p>In this article, we’ll explore <strong>State Lifetime</strong>, <strong>Conditional Branches</strong>, and <strong>.id()</strong> and how they work together to determine the lifetime of state in SwiftUI.</p><h3>State Lifetime</h3><p>If identity determines whether SwiftUI considers a view to be the same view, then <strong>state lifetime is the most important consequence of that decision</strong>.</p><p>Property wrappers such as @State, @StateObject, and @FocusState do not store their underlying data directly inside view struct. The view struct is a value and can be recreated freely. SwiftUI keeps the associated state storage in its internal machinery and associates that storage with the view’s <strong>identity</strong>.</p><p>That leads to:</p><blockquote>Whenever a view’s identity changes, its associated state is replaced.</blockquote><p>This means @State and @StateObject storage can be torn down and re-initialized when SwiftUI determines that the old view and new view represent different identities.</p><h4>Stable Identity, Persistent State</h4><p>A common misconception is that recreating a view struct means recreating its state. It does not.</p><p>SwiftUI can initialize and re-evaluate a view value many times while keeping its identity stable. As long as SwiftUI recognizes the view as the same conceptual view, its associated state storage remains alive.</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><br>            Button(&quot;Increment&quot;) {<br>                count += 1<br>            }<br>        }<br>    }<br>}</pre><p>CounterView may be recreated as SwiftUI evaluates the hierarchy, but count does not reset on every body evaluation. Its storage belongs to the view’s identity, not to a particular instance of the CounterView struct.</p><p>The same thing is particularly important for @StateObject, the object is created once for the lifetime of that identity, rather than once every time the body runs.</p><h4>When Identity Changes</h4><p>When identity changes, SwiftUI considers the old view and the new view to be different. The old state is destroyed, and new state storage is created for the new identity.</p><p>So when state appears to “randomly reset,” the first question is: <strong>“Did this view’s identity change?”</strong></p><p>For example:</p><pre>if isActive {<br>    CounterView()<br>} else {<br>    CounterView()<br>}</pre><p>Although the two branches contain the same CounterView type, they occupy different conditional branches and therefore have different structural identities.</p><p>If isActive switches, SwiftUI can destroy the state associated with the previous branch and create a new state for the other one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NIq7pjnw4kyBgisbP88SRA.png" /></figure><h4>Removing and Reordering Views</h4><p>The same rule explains what happens when a view leaves the hierarchy. <strong>View removed from the tree means its state is destroyed.</strong></p><p>But reordering is different when identity remains stable. Consider a ForEach:</p><pre>ForEach(items) { item in<br>    ItemRow(item: item)<br>}</pre><p>If each item has a stable identity through Identifiable, SwiftUI can recognize an item even after its position changes. The associated state can therefore <strong>move with the item</strong> rather than being recreated simply because its index changed.</p><p>This is one of the major reasons stable identity is essential for dynamic collections.</p><h4>The .id(UUID()) Trap</h4><p>One of the easiest ways to accidentally destroy state is to generate a new identity during every render:</p><pre>// New identity every time<br>ContentView()<br>   .id(UUID())</pre><p>UUID() produces a new value each time this expression is evaluated. That means SwiftUI sees a new identity, tears down the previous state, and creates a fresh state.</p><p>The view may look like the same view on screen, but SwiftUI is being told that it is a different view every time.</p><p>B<strong>ody re-evaluation is normal; identity replacement is what resets state.</strong> When debugging unexpected state loss, trace the identity before blaming the state property wrapper.</p><h3>Conditional Branches</h3><p>Conditional branches are one of the clearest places where SwiftUI’s <strong>structural identity</strong> becomes visible.</p><p>When if, else, or switch is used inside a ViewBuilder, SwiftUI represents the conditional as _ConditionalContent&lt;ViewAType, ViewBType&gt;. This structure gives the <strong>true and false branches distinct identities</strong> within the view hierarchy.</p><pre>if showA {<br>    CounterView() // true branch<br>} else {<br>    CounterView() // false branch<br>}</pre><p>Even though both branches contain the same CounterView type, they are <strong>not the same view identity</strong>. They occupy different structural branches.</p><p>When showA changes, SwiftUI switches the active branch:</p><pre>showA = true<br>↓<br>_ConditionalContent<br>├── true → CounterView (active)<br>└── false → CounterView<br><br>showA = false<br>↓<br>_ConditionalContent<br>├── true → CounterView<br>└── false → CounterView (active)</pre><p>The concrete type stays the same, but the <strong>structural identity changes</strong>. SwiftUI can therefore discard the state associated with the previous branch and create fresh state for the new one.</p><p>This is why conditional branches can reset @State, recreate @StateObject, or affect transitions and animations. The issue is not the if itself; it is that the condition changes <strong>which structural identity is active</strong>.</p><h4>Preserving Identity Across Conditions</h4><p>If a condition changes only a view’s <strong>appearance or behavior</strong>, rather than which view fundamentally exists, keep the view in the hierarchy and change its properties.</p><pre>// View is removed and reinserted<br>if isVisible {<br>    CounterView()<br>}<br><br>// Same view identity<br>CounterView()<br>    .opacity(isVisible ? 1 : 0)</pre><p>Similarly, .zIndex() can change visual stacking while keeping the view present:</p><pre>CounterView()<br>  .opacity(isVisible ? 1 : 0)<br>  .zIndex(isVisible ? 1 : 0)</pre><p>The key distinction is that <strong>hiding a view is not the same as removing it from the tree</strong>. A view that remains in the hierarchy can retain its identity and associated state.</p><p>You can also keep a stable container while conditionally changing one of its children:</p><pre>VStack {<br>    HeaderView()<br><br>    if showDetails {<br>        DetailsView()<br>    }<br><br>    FooterView()<br>}</pre><p>Here, the VStack, HeaderView, and FooterView remain structurally stable while only DetailsView participates in the conditional branch.</p><blockquote>If the condition determines which view exists, use a conditional branch. If it only changes how an existing view appears or behaves, prefer changing its data or modifiers.</blockquote><p>For stateful views, this distinction matters because removing a view from the hierarchy can end its <strong>state lifetime</strong>.</p><h3>.id()</h3><p>If structural identity is SwiftUI’s implicit way of determining what a view is, .id() gives you a way to explicitly control that identity.</p><p>The .id(_:) modifier associates a view with an identity value that you provide:</p><pre>ContentView()<br>   .id(user.id)</pre><p>The value passed to .id() becomes part of the view’s identity. As long as that value remains stable, SwiftUI can continue treating the view as the same conceptual view across updates.</p><p>When the value changes, however, SwiftUI treats the view as having a new identity.</p><pre>ContentView()<br>.id(selectedUserID)</pre><p>If selectedUserID changes from 1 to 2, SwiftUI does not simply update the existing ContentView. Conceptually, the old identity is removed and a new identity is inserted.</p><p>This distinction is particularly important for state:</p><pre>struct ProfileView: View {<br>    let userID: Int<br><br>    @State private var counter = 0<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;User: \(userID)&quot;)<br>            Text(&quot;Counter: \(counter)&quot;)<br><br>            Button(&quot;Increment&quot;) {<br>                counter += 1<br>            }<br>        }<br>    }<br>}</pre><p>Now consider:</p><pre>ProfileView(userID: selectedUserID)<br>    .id(selectedUserID)</pre><p>When selectedUserID changes, the identity of ProfileView changes as well. Its previous state storage no longer belongs to the active identity, so the @State value is initialized again for the new identity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RKfWfXPyacq_N3kRDu6_Rg.png" /></figure><p>This makes .id() useful when you <strong>intentionally want to reset a view’s state</strong>.</p><p>For example, switching between users in a detail screen may require the entire screen to start from a clean state:</p><pre>ProfileView(userID: selectedUserID)<br>    .id(selectedUserID)</pre><p>It can also be useful when you deliberately need to restart view-local behaviour, such as resetting a certain animation or scroll-related state.</p><p>However, .id() should not be treated as a generic “refresh this view” mechanism. Changing identity has lifecycle consequences because SwiftUI now considers the view a different instance.</p><h4>The .id(UUID()) Trap</h4><p>One of the most common mistakes is generating a new identity during every evaluation:</p><pre>// New identity on every evaluation<br>ContentView()<br>.id(UUID())</pre><p>Every evaluation produces a different UUID:</p><p>Render 1 — UUID A — Identity A</p><p>Render 2 — UUID B — Identity B</p><p>Render 3 — UUID C — Identity C</p><p>From SwiftUI’s perspective, these are three different view identities. Any state associated with the previous identity can therefore be discarded and recreated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPH6xeewTiBVlQrMZmrOMA.png" /></figure><p>The rule is simple: <strong>an explicit ID should be stable for as long as you want the view to represent the same conceptual element.</strong></p><p>This same identity model appears in other SwiftUI APIs. ForEach uses explicit data identity to distinguish its elements, while ScrollViewReader uses an ID to locate a particular view when calling scrollTo.</p><pre>ForEach(items, id: \.id) { item in<br>    ItemRow(item: item)<br>}</pre><p>Here, the ID answers the question: <em>Which item is this?</em></p><p>With .id(), the question is slightly different: <em>Should SwiftUI consider this view to be the same view as before?</em></p><p>That distinction makes .id() powerful but also easy to misuse. Use it when you intentionally need to define an identity boundary, not as a way to force SwiftUI to “rebuild” arbitrary UI.</p><blockquote>Use .id() when a change in data should represent a genuinely new view identity. Keep the ID stable otherwise.</blockquote><p>That brings us to the end of this part of our Indian yellow series 😝 .</p><p>In the <a href="https://medium.com/@raajveer/swiftui-anyview-navigation-and-rendering-advanced-view-tree-guide-7bcfe1e9cb62">next part</a>, we’ll continue deeper into the <strong>SwiftUI View Tree</strong> and explore how these concepts influence rendering, updates, and performance.</p><p>See ya 👋</p><h3>Thanks for reading Cross Commit</h3><p>Before you go:</p><figure><img alt="Follow Cross Commit: practical Swift, Kotlin and mobile AI stories from engineers who ship real apps" src="https://cdn-images-1.medium.com/max/1024/1*aojKTaZmGnisRaGyAL1g0g.png" /><figcaption>Follow Cross Commit on Medium: <a href="https://medium.com/cross-commit">medium.com/cross-commit</a></figcaption></figure><p>👉 <strong>Clap</strong> and <strong>follow</strong> <a href="https://medium.com/u/a769be0a8ae0">Rajveer</a> so their next story lands in your feed 👏</p><p>👉 Want their stories by email? After you follow, tap <strong>Following</strong> on their profile and choose <strong>Email notifications on</strong> 📩</p><p>👉 <strong>Follow </strong><a href="https://medium.com/cross-commit"><strong>Cross Commit</strong></a> for practical iOS, Android and mobile AI stories from engineers who ship real apps</p><p>👉 Writing about Swift, Kotlin or mobile AI? Cross Commit is open to writers worldwide. Leave a response below and we’ll get in touch ✍️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4373b6d59b5b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cross-commit/swiftui-state-lifetime-and-identity-conditional-branches-and-id-explained-4373b6d59b5b">SwiftUI State Lifetime and Identity: Conditional Branches and .id() Explained</a> was originally published in <a href="https://medium.com/cross-commit">Cross Commit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI View Tree Explained: View Identity and Structural Identity]]></title>
            <link>https://medium.com/cross-commit/swiftui-view-tree-explained-view-identity-and-structural-identity-8aa9ada8dc9e?source=rss-a769be0a8ae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aa9ada8dc9e</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[view-identity]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swiftui-view-tree]]></category>
            <category><![CDATA[swiftui-performance]]></category>
            <dc:creator><![CDATA[Rajveer]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 05:37:02 GMT</pubDate>
            <atom:updated>2026-10-20T11:54:21.540Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHd-0Yogpv_2wOjKneKoRA.png" /></figure><p>Have you ever toggled a simple if condition in SwiftUI, only to see your @State reset? The reason lies in how SwiftUI manages its <strong>View Tree</strong>. Whenever state changes, SwiftUI evaluates the affected views, compares the new view description with the previous one, and updates the UI. At the center of this process is <strong>identity</strong>—it tells SwiftUI whether a view is the same as before. Stable identity helps preserve state, while a changed identity can create a new view and reset its state. Understanding <strong>view structure, identity, and state lifetime</strong> makes SwiftUI’s behaviour much easier to predict.</p><h3>What Is the SwiftUI View Tree?</h3><p>At its surface, SwiftUI appears to be a collection of nested views. But beneath that declarative syntax, it maintains a structure that determines how those views are evaluated, compared, and updated.</p><p>A SwiftUI view’s body property produces a <strong>tree of view values</strong>. These values describe what the UI should look like at a given moment, but they are <strong>ephemeral</strong>: SwiftUI creates them for evaluation and comparison, then discards them. The view value itself is not the persistent UI object.</p><p>The persistent machinery behind this process is commonly associated with <strong>AttributeGraph,</strong> a <strong>directed acyclic graph (DAG)</strong> that tracks dependencies throughout the UI. Rather than treating every view as an isolated element, SwiftUI uses this dependency structure to understand which parts of the interface are affected when data changes.</p><p>When state changes, SwiftUI re-evaluates the affected body and performs a <strong>structural diff</strong>. It compares the newly produced view tree with the previous one, using structure and identity to determine which parts need updating and which can remain unchanged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*REU9qBGYEKp2PHb-TdiVug.png" /></figure><p><strong>Reference:</strong><a href="https://developer.apple.com/documentation/xcode/understanding-and-improving-swiftui-performance"><strong> Apple — Understanding and Improving SwiftUI Performance</strong></a><strong>.</strong></p><p>It is important to distinguish the conceptual model from the implementation details. <strong>AttributeGraph is a private C++/Swift framework</strong> that powers SwiftUI’s dependency tracking, diffing, and recomputation mechanisms. Developers interact with SwiftUI’s public APIs, while the exact internal implementation remains opaque and can change across OS releases.</p><h3>View Identity</h3><p><strong>View identity</strong> is how SwiftUI determines whether a view represents the <strong>same conceptual UI element</strong> or a distinct one across multiple updates. SwiftUI does not treat every newly evaluated view value as a completely new view. Instead, identity allows it to connect the new description with what existed before.</p><p>SwiftUI works with two forms of identity: <strong>structural identity</strong> and <strong>explicit identity</strong>.</p><h4>Structural Identity</h4><p><strong>Structural identity</strong> is implicit. SwiftUI derives it from a view’s <strong>type and position within the hierarchy</strong>. The structure of your body therefore becomes part of how SwiftUI identifies views even when you never explicitly provide an ID.</p><p>For example, these two branches may look similar on screen, but SwiftUI can treat them as structurally different views because they occupy different branches of the view hierarchy:</p><pre>if isLoggedIn {<br>    ProfileView()<br>} else {<br>    LoginView()<br>}</pre><p>The identity here comes from the structure SwiftUI sees, not from a manually assigned identifier.</p><h4>Explicit Identity</h4><p><strong>Explicit identity</strong> is provided by you when structural identity alone is not enough. This is especially important when working with dynamic collections.</p><p>A common example is ForEach:</p><pre>ForEach(items, id: \.id) { item in<br>    ItemRow(item: item)<br>}</pre><p>You can also explicitly replace a view’s identity using the .id(_:) modifier:</p><pre>ContentView()<br>    .id(selectedID)</pre><p>Changing that ID tells SwiftUI that the view should now be treated as a <strong>different identity</strong>, even if the surrounding structure remains the same.</p><h4>Why Identity Matters</h4><p>Identity is what allows SwiftUI to understand that two different view values may actually represent <strong>different states of the same conceptual UI element</strong>.</p><p>Consider a list where an item moves from one position to another. If its identity remains stable, SwiftUI can recognize that it is the same item and update its position rather than treating it as a completely new view.</p><pre>ForEach(items, id: \.id) { item in<br>    ItemRow(item: item)<br>}</pre><p>If the identity changes, however, SwiftUI treats the old and new views as <strong>distinct</strong>. They can then transition independently, for example, one view can fade out while another fades in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTgSQb6z7f0MSNTeAb2L9Q.png" /></figure><p>This is why identity has consequences far beyond simply rendering the correct UI. It directly affects <strong>state lifetime</strong>, including @State and @StateObject; <strong>animations and transitions</strong>; <strong>performance</strong>, because identity influences how much work SwiftUI needs to reconcile; and <strong>navigation state</strong>, where losing identity can cause navigation-related state to be recreated.</p><blockquote><strong>Type and position give SwiftUI structural identity; explicit IDs let you take control when the data itself defines what “the same view” means.</strong></blockquote><h3>Structural Identity</h3><p><strong>Structural identity</strong> is the implicit identity SwiftUI derives from a view’s <strong>type and position in the view hierarchy</strong>. It is what allows SwiftUI to identify views without requiring you to manually assign an ID to every element.</p><p>SwiftUI generates this identity from the structure of your ViewBuilder hierarchy. In other words, the shape of your view code becomes part of the identity model.</p><p>Consider:</p><pre>VStack {<br>    Text(&quot;A&quot;) // identity: VStack &gt; Text at index 0<br>    Text(&quot;B&quot;) // identity: VStack &gt; Text at index 1<br>}</pre><p>Here, the two Text views have the same type, but they occupy different positions in the hierarchy. Their structural identities are therefore different. Reordering them changes those structural positions:</p><pre>VStack {<br>    Text(&quot;B&quot;) // now index 0<br>    Text(&quot;A&quot;) // now index 1<br>}</pre><p>From SwiftUI’s perspective, this is not merely “the same two texts in a different order.” Their <strong>structural identity has changed</strong>, which can affect associated state and how updates are reconciled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLZYKHnhVtzxaREFV0HK8w.png" /></figure><h4>ForEach and Data Identity</h4><p>Dynamic collections introduce another important layer. ForEach uses <strong>data identity</strong> through its id parameter or Identifiable conformance. Here, identity comes from the data rather than simply from a view’s position.</p><pre>struct Item: Identifiable {<br>    let id: UUID<br>    let name: String<br>}<br><br>ForEach(items) { item in<br>    ItemRow(item: item)<br>}</pre><p>Because each element has a stable id, SwiftUI can distinguish one item from another even when their positions change. This allows it to <strong>move, insert, and delete rows while preserving the state associated with each item</strong>.</p><p>That distinction is crucial in lists. If an item moves from index 2 to index 0 but retains the same data identity, SwiftUI can understand that the item itself moved. Without stable identity, position can become the only signal available, leading to state being associated with the wrong element or recreated unnecessarily.</p><h4>Conditional Branches Have Different Identities</h4><p>Conditional logic inside a ViewBuilder introduces another structural-identity rule that often catches developers off guard.</p><p>An if, else, or switch does not simply mutate one existing view. SwiftUI represents conditional branches using _ConditionalContent, with each branch having its own structural identity.</p><p>For example:</p><pre>if isLoading {<br>    ProgressView()<br>} else {<br>    ContentView()<br>}</pre><p>Conceptually, SwiftUI sees these as <strong>two different structural views</strong>. Switching from ProgressView to ContentView means switching from one identity to another.</p><p>This is particularly important when both branches contain what appears to be the same underlying view:</p><pre>if expired {<br>    content.opacity(0.3)<br>} else {<br>    content<br>}</pre><p>Even though content looks like the same conceptual view, placing it in two conditional branches can give SwiftUI two different structural identities.</p><h4>The Inert Modifier Rule</h4><p>When the condition only changes a <strong>modifier value</strong>, you can often preserve a single structural identity by keeping the view outside the conditional:</p><pre>// Two structural identities<br>if expired {<br>    content.opacity(0.3)<br>} else {<br>    content<br>}<br><br>// One structural identity<br>content.opacity(expired ? 0.3 : 1.0)</pre><p>Now there is only one content node in the hierarchy. The condition changes the modifier’s value rather than choosing between two structural branches.</p><p>This pattern is sometimes described through the <strong>inert-modifier rule</strong>: certain modifier values are effectively inert, meaning SwiftUI can optimize them away when they have no visual effect, for example, opacity(1) or padding(0).</p><pre>content<br>    .opacity(expired ? 0.3 : 1.0)<br>    .padding(0)</pre><p>The important distinction is not that modifiers are universally “free,” but that <strong>inert modifier values can be pruned by SwiftUI without introducing a new structural identity</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9XRPDma8YTNq0Ghx4ocIw.png" /></figure><blockquote><strong>If a condition changes what the view fundamentally is, a structural branch is appropriate; if it only changes how the same view looks or behaves, prefer a modifier on the shared view when possible.</strong></blockquote><p>We will discus more about SwiftUI View Tree in <a href="https://medium.com/@raajveer/swiftui-state-lifetime-and-identity-conditional-branches-and-id-explained-4373b6d59b5b">next part</a>. Until then, Happy SwiftUI!!</p><h3>Thanks for reading Cross Commit</h3><p>Before you go:</p><figure><img alt="Follow Cross Commit: practical Swift, Kotlin and mobile AI stories from engineers who ship real apps" src="https://cdn-images-1.medium.com/max/1024/1*aojKTaZmGnisRaGyAL1g0g.png" /><figcaption>Follow Cross Commit on Medium: <a href="https://medium.com/cross-commit">medium.com/cross-commit</a></figcaption></figure><p>👉 <strong>Clap</strong> and <strong>follow</strong> <a href="https://medium.com/u/a769be0a8ae0">Rajveer</a> so their next story lands in your feed 👏</p><p>👉 Want their stories by email? After you follow, tap <strong>Following</strong> on their profile and choose <strong>Email notifications on</strong> 📩</p><p>👉 <strong>Follow </strong><a href="https://medium.com/cross-commit"><strong>Cross Commit</strong></a> for practical iOS, Android and mobile AI stories from engineers who ship real apps</p><p>👉 Writing about Swift, Kotlin or mobile AI? Cross Commit is open to writers worldwide. Leave a response below and we’ll get in touch ✍️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aa9ada8dc9e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cross-commit/swiftui-view-tree-explained-view-identity-and-structural-identity-8aa9ada8dc9e">SwiftUI View Tree Explained: View Identity and Structural Identity</a> was originally published in <a href="https://medium.com/cross-commit">Cross Commit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoiding Unnecessary Body Invalidation in SwiftUI]]></title>
            <link>https://medium.com/@raajveer/avoiding-unnecessary-body-invalidation-in-swiftui-f7313ea9e08e?source=rss-a769be0a8ae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7313ea9e08e</guid>
            <category><![CDATA[swiftui-performance]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui-views]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[view-invalidation]]></category>
            <dc:creator><![CDATA[Rajveer]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 04:52:57 GMT</pubDate>
            <atom:updated>2026-09-07T04:52:57.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lvnGePLXwHbHMIPRhHB1gA.png" /></figure><p>SwiftUI’s declarative syntax makes it easy to build interfaces, but it also hides an important performance consideration: <strong>body invalidation</strong>.</p><p>Whenever SwiftUI determines that a view’s body may need to be re-evaluated, it calls the body property again. If this happens too often especially in a scrolling list or complex view hierarchy, it can lead to dropped frames and sluggish interactions.</p><p>This article explores what <strong>body invalidation</strong> is, why it happens, and how to avoid unnecessary invalidations using techniques such as EquatableView, correct property wrappers, and view decomposition. Let’s go!!</p><p><strong>SwiftUI body invalidation</strong> is the process by which SwiftUI marks a view as needing a new body value. When a dependency changes such as a @State value, an @ObservedObject’s @Published property, or an environment value SwiftUI invalidates the views that depend on that data.</p><p>It’s important to distinguish <strong>body invalidation</strong> from <strong>view redraw / render</strong>:</p><ul><li><strong>Body invalidation</strong> means SwiftUI re-evaluates the body property to produce a new view value.</li><li><strong>View redraw / render</strong> means the resulting view tree is actually committed to the screen.</li></ul><p>SwiftUI uses a <strong>diffing</strong> algorithm to compare the old and new view values. If the resulting view tree is unchanged, no actual rendering occurs but the body still computed, which costs CPU time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_H1ZQ7vWop5X9LaKHCZ1yg.png" /></figure><p><strong>View identity</strong> also plays an important role. Stable identities in ForEach and conditional branches can reduce the amount of diffing and help prevent unnecessary state loss.</p><p>In short, invalidating body is often necessary. The performance problem comes when SwiftUI invalidates it more than required.</p><h3>Common Causes of Unnecessary Body Invalidation</h3><p>Several patterns can cause SwiftUI to call body more often than necessary.</p><h4>@Published Updates on an ObservableObject</h4><p>Before iOS 17, any change to a @Published property on an observed object triggers objectWillChange, invalidating <strong>every view that uses that object</strong>, even if the view does not read the property that changed. This is a major source of over-invalidation.</p><pre>final class UserViewModel: ObservableObject {<br>    @Published var name = &quot;Miraj&quot;<br>    @Published var isLoading = false<br>}<br><br>struct ProfileView: View {<br>    @ObservedObject var viewModel: UserViewModel<br><br>    var body: some View {<br>        Text(viewModel.name)<br>    }<br>}</pre><p>Here, ProfileView reads only name. Before iOS 17, changing <em>isLoading</em> can still invalidate ProfileView because the observed object publishes the change.</p><h4>Multiple Observed Objects in One View</h4><p>A view that observes two or more <em>ObservableObject</em> instances can invalidate when <strong>any of them publishes a change</strong>. This increases the number of updates the view may need to process.</p><pre>struct DashboardView: View {<br>    @ObservedObject var user: UserViewModel<br>    @ObservedObject var settings: SettingsViewModel<br><br>    var body: some View {<br>        Text(user.name)<br>            .font(settings.font)<br>    }<br>}</pre><p>A change published by either user or settings can invalidate DashboardView.</p><h4>Using @ObservedObject When @StateObject Is More Appropriate</h4><p><em>@ObservedObject</em> does not own the object. When the object’s identity changes, the view can resubscribe to the new instance. If a parent recreates the object during an update, this can lead to unnecessary invalidation.</p><pre>struct ParentView: View {<br>    @State private var refresh = false<br><br>    var body: some View {<br>        ChildView(viewModel: UserViewModel())<br>    }<br>}<br><br>struct ChildView: View {<br>    @ObservedObject var viewModel: UserViewModel<br><br>    var body: some View {<br>        Text(viewModel.name)<br>    }<br>}</pre><p>When a view is responsible for creating and owning an observable object, <em>@StateObject</em> is the appropriate ownership model.</p><h4>Parent State Changes Cascading into Child Views</h4><p>If a parent reads a <em>@State</em> value and passes it to a child, changing that state invalidates the parent’s body. The child may also invalidate if it reads the same data, multiplying invalidations down the hierarchy.</p><h4>Unused @Published Properties</h4><p>Declaring many <em>@Published</em> properties on an observed object can also increase invalidation. Before iOS 17, a view may be invalidated when <strong>any</strong> published property changes, even when the view only uses one of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2k7LuOtKjTsIX07IN2HrQ.png" /></figure><p>The problem is not the number of properties itself, but the broad invalidation caused by observing the entire object.</p><h3>How to Detect SwiftUI Body Invalidation</h3><p>SwiftUI provides a useful debugging tool for seeing why a view’s body is being called.</p><h4>Self._printChanges()</h4><p>Add Self._printChanges() at the top of the view’s body:</p><pre>var body: some View {<br>    let _ = Self._printChanges()<br><br>    // ...<br>}</pre><p>When SwiftUI invalidates the view, _printChanges() prints the properties that changed and triggered the invalidation. For example:</p><p>MyView: _someState changed.</p><p>MyView: _model.objectWillChange changed.</p><p>_printChanges() is a private, underscore-prefixed API intended for debugging, so it should be removed from production code.</p><p>You can also set breakpoints inside body to inspect how often it is called during interactions. Combine this with <strong>Instruments’ SwiftUI template</strong> to measure the actual render cost rather than relying only on how frequently body is evaluated.</p><h3>Strategies to Avoid Unnecessary Body Invalidation</h3><h4>Use EquatableView and the .equatable() Modifier</h4><p>One of the most direct ways to prevent unnecessary body evaluation is to make your view conform to Equatable and apply the <em>.equatable() </em>modifier. When SwiftUI receives a new value for a view that has this modifier, it first checks the view’s == implementation. If the old and new values are equal, SwiftUI skips calling body entirely. This works because the modifier essentially tells SwiftUI, “<em>Before you recompute this view, compare it to the previous one and decide whether the update is needed.</em>”</p><p>Here’s a simple example:</p><pre>struct UserRow: View, Equatable {<br>    let name: String<br>    let age: Int<br><br>    static func == (lhs: UserRow, rhs: UserRow) -&gt; Bool {<br>        lhs.name == rhs.name &amp;&amp; lhs.age == rhs.age<br>    }<br><br>    var body: some View {<br>        Text(&quot;\(name), \(age)&quot;)<br>    }<br>}<br><br>// Usage:<br>UserRow(name: user.name, age: user.age)<br>    .equatable()</pre><p>According to Apple’s documentation, the <em>.equatable()</em> modifier prevents the view from updating its child view when the new value is the same as the old value. In practice, this means that if UserRow receives the same name and age as before, body is not called at all.</p><p>This technique works best for leaf views that depend only on a small number of value‑type inputs, such as strings, numbers, or simple structs. It is less effective and often not applicable when the view contains its own <em>@State</em> or observes an object, because those changes are not captured by the Equatable comparison. In those cases, other strategies are needed.</p><h4>Choose the Right Property Wrapper</h4><p>Property wrappers play a key role in determining when and how often a view’s body is invalidated. Selecting the appropriate wrapper for each piece of data can dramatically reduce unnecessary invalidation.</p><p><strong>@StateObject vs @ObservedObject</strong></p><p><em>@StateObject </em>creates and owns an ObservableObject. The object’s identity remains stable across view updates, which means the view does not resubscribe to the object’s publisher unnecessarily. You should use <em>@StateObject</em> in the view that creates the object. <em>@ObservedObject</em>, on the other hand, is intended for objects that are passed in from a parent that owns them.</p><p>A common mistake is using <em>@ObservedObject</em> in a child view when the parent re‑creates the object during an update. That can cause the child to resubscribe and invalidate when the object’s identity changes. With <em>@StateObject</em>, the owning view keeps the same instance, avoiding those extra invalidations.</p><p><strong>@State vs @StateObject</strong></p><p>@State is designed for local, value‑type state a string, an integer, a boolean. Changes to @State invalidate only the view that reads that state, not parent or sibling views. For small, view‑private data, @State limits the invalidation scope effectively. @StateObject is for reference‑type objects that the view owns and observes.</p><p><strong>Observation framework (iOS 17+)</strong></p><p>With iOS 17 and later, the modern <em>@Observable</em> macro offers precise dependency tracking. Instead of invalidating every view that observes an object when any<em> @Published</em> property changes, SwiftUI only invalidates a view if the specific properties accessed in its body change. This eliminates the classic over‑invalidation problem associated with ObservableObject. If your deployment target allows it, migrating to <em>@Observable</em> is one of the most effective ways to avoid unnecessary body invalidation.</p><h4>Break Views into Smaller Components</h4><p>SwiftUI’s invalidation system is granular: when a view reads a <em>@State</em> or <em>@ObservedObject</em> property, only that view’s body is invalidated. If you keep all state at the top of a large view, every state change invalidates the entire subtree below it, including child views that do not depend on that state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhifaJr6x9Z-IqxbC6vZZA.png" /></figure><p>By extracting the parts that depend on state into small, focused subviews, you limit invalidation to those subviews. Consider this example:</p><pre>struct ContentView: View {<br>    @State private var searchText = &quot;&quot;<br><br>    var body: some View {<br>        VStack {<br>            SearchBar(text: $searchText)   // invalidates only SearchBar<br>            UserList()                     // unaffected<br>        }<br>    }<br>}</pre><p>Here, only SearchBar needs to be invalidated when searchText changes. The UserList view, which does not read searchText, remains untouched. This approach not only reduces unnecessary invalidation but also makes your view hierarchy easier to reason about.</p><h4>Use Local State and Value Types</h4><p>A guiding principle for SwiftUI performance is to keep state as close to where it is used as possible. If a value is needed only by a single view, store it as <em>@State</em> in that view rather than in a shared <em>ObservableObject</em>. This prevents unrelated views from being invalidated when the value changes.</p><p>Equally important is the choice of data types. Prefer value types struct and enum for data passed between views. Value types allow SwiftUI’s diffing to work efficiently and enable Equatable conformance, which you can combine with the <em>.equatable()</em> modifier. Avoid passing large reference‑type objects into leaf views unless the leaf view actually needs to observe them; otherwise, every property change on that object may trigger invalidations in views that don’t really depend on it.</p><h3>Common Mistakes and Fixes</h3><p>Many unnecessary invalidations come from a handful of avoidable patterns. Using <em>@ObservedObject</em> in every child view causes resubscription and extra updates; instead, use <em>@StateObject</em> in the view that creates the object and passes it down only when children truly need to observe it. Similarly, stuffing all app state into one giant ObservableObject invalidates every view that observes it, even when only a small piece changes, split state into focused observable objects so each view observes only what it uses. Another easy oversight is forgetting to apply .equatable() to a view that already conforms to Equatable; the conformance alone does nothing without the modifier. Finally, many developers assume body is called rarely; use Self._printChanges() to see exactly how often it runs and remove invalidations that serve no purpose.</p><p>Body invalidation is a normal part of SwiftUI’s update process, but excessive invalidation can become a performance problem when views are complex or frequently updated. The goal is not to prevent <em>body</em> from being evaluated altogether, but to make sure SwiftUI is doing that work only when necessary.</p><p>So, see you in next one with something new. Until then, Happy SwiftUI!! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7313ea9e08e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI @Environment: Performance Optimisation Through Smarter Architecture]]></title>
            <link>https://medium.com/@raajveer/swiftui-environment-performance-optimisation-through-smarter-architecture-051e50db381d?source=rss-a769be0a8ae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/051e50db381d</guid>
            <category><![CDATA[environment-swiftui]]></category>
            <category><![CDATA[swiftui-performance]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[performance-optimisation]]></category>
            <dc:creator><![CDATA[Rajveer]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 05:11:41 GMT</pubDate>
            <atom:updated>2026-08-31T05:11:41.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTt9nXB0qGh4SI_CJ5B9ZA.png" /></figure><p>In <a href="https://medium.com/@raajveer/swiftui-environment-the-overlooked-performance-overhead-37307b3b9e7d">Part 1</a>, we saw that an environment write makes SwiftUI traverse the entire subtree beneath the modifier. Even views that are ultimately skipped still pay the cost of the dependency check.</p><p>In this post, we’ll turn those ideas into practical patterns: how to isolate high-frequency data, when<em> @Equatable</em> can help, and how to use the SwiftUI Instrument to find and measure the actual bottlenecks.</p><h3>The “Scoped Listener” Pattern</h3><p>Apple explicitly warns against putting frequently changing values, such as timers or geometry data, into the Environment. Location data is a good example:</p><pre>class LocationManager: ObservableObject {<br>    @Published var currentLocation: CLLocation?<br>}</pre><p>If this manager is injected at the root and a deeply nested view reads currentLocation, every location update can propagate through the entire subtree. Most of those views don’t need the location, but SwiftUI still has to perform the dependency checks.</p><p>The better approach is to keep the <strong>manager</strong> available through the Environment while moving the actual location dependency into a small, dedicated view:</p><pre>@main<br>struct LocationSampleApp: App {<br>    @StateObject private var locationManager = LocationManager()<br><br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>                .environmentObject(locationManager)<br>        }<br>    }<br>}<br><br>/// The parent doesn&#39;t read the changing location:<br>struct ContentView: View {<br>    var body: some View {<br>        VStack {<br>            Text(&quot;Welcome&quot;)<br>            LocationDisplayView()<br>        }<br>    }<br>}<br><br>/// Instead, only the small child reads it:<br>struct LocationDisplayView: View {<br>    @EnvironmentObject var locationManager: LocationManager<br><br>    var body: some View {<br>        if let location = locationManager.currentLocation {<br>            Text(&quot;Lat: \(location.coordinate.latitude)&quot;)<br>            Text(&quot;Long: \(location.coordinate.longitude)&quot;)<br>        }<br>    }<br>}</pre><p>Now, when the location changes, ContentView can be skipped while LocationDisplayView handles the actual update. The environment propagation still happens, but the expensive body work is confined to the smallest view that needs the changing data.</p><p>This is the essence of the <strong>Scoped Listener</strong> pattern: keep stable dependencies higher in the hierarchy, but keep frequently changing data consumers small and focused.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S4yqsshnOoEASnuySYs4Fg.jpeg" /></figure><h3>Throttle High-Frequency Updates at the Source</h3><p>The Scoped Listener limits <strong>where</strong> an update is handled, but it doesn’t reduce <strong>how often</strong> that update reaches SwiftUI.</p><p>For example, if location data changes 10 times per second and the affected subtree contains 500 views, SwiftUI still performs those dependency checks 10 times every second. Most of that work is unnecessary because only a small part of the UI actually needs the latest location.</p><p>The next step is therefore to reduce the number of updates <strong>before they enter SwiftUI’s update cycle</strong>.</p><p>For location data, you often don’t need to publish every GPS reading. If the UI only needs to react after the user has moved a meaningful distance, filter the updates at the source:</p><pre>func locationManager(<br>    _ manager: CLLocationManager,<br>    didUpdateLocations locations: [CLLocation]<br>) {<br>    guard let newLocation = locations.last else { return }<br><br>    if let oldLocation = lastLocation,<br>       newLocation.distance(from: oldLocation) &lt; 10 {<br>        return<br>    }<br><br>    lastLocation = newLocation<br>}</pre><p>Now SwiftUI receives a new value only when the user has moved more than 10 meters. For other rapidly changing data, the same principle can be implemented with Combine’s throttle or debounce operators.</p><p>The important part isn’t the specific API. It’s <strong>where the filtering happens</strong>:</p><blockquote><strong>Filter high-frequency data before publishing it to SwiftUI, rather than making SwiftUI process every update and filtering later.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m4iLgjO7yQvIU7Fg7nUSmQ.jpeg" /></figure><h3>Make Your Views Explicitly Equatable</h3><p>SwiftUI needs to compare a view’s inputs to determine whether its body actually needs to run again. This becomes harder when a view contains values that cannot be meaningfully compared, such as closures or certain reference types. In those cases, SwiftUI may conservatively re-evaluate the view during parent updates, even when its visible output hasn’t changed.</p><p>This matters particularly in frequently updating views and large lists, where a small amount of unnecessary work can quickly add up.</p><p>For this article, we’ll keep the solution simple: <strong>use Swift’s built-in Equatable conformance to make the view’s meaningful inputs explicit.</strong></p><pre>struct ProductCard: View, Equatable {<br>    let product: Product<br><br>    static func == (lhs: Self, rhs: Self) -&gt; Bool {<br>        lhs.product == rhs.product<br>    }<br><br>    var body: some View {<br>        VStack {<br>            Text(product.name)<br>            Text(product.price, format: .currency(code: &quot;USD&quot;))<br>        }<br>    }<br>}</pre><p>The equality check should focus on the properties that actually determine what the view renders. If a view also has a closure or another value that doesn’t affect its visual output, it doesn’t necessarily need to participate in the comparison.</p><p>The trade-off is straightforward: you have to maintain the == implementation yourself, but you gain an explicit and predictable diffing rule.</p><p>The principle is:</p><blockquote><strong>Make view diffability explicit, especially for views inside frequently updating hierarchies.</strong></blockquote><p>Combined with the previous rules, the strategy becomes: <strong>reduce how often updates arrive, keep their scope small, and make the remaining views easy to compare.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VOAZMzTgUfLIjQuMpilBA.jpeg" /></figure><h3>The iOS 17+ Shift: @Observable vs ObservableObject</h3><p>With ObservableObject, SwiftUI’s observation is centered around the object. When any @Published property changes, views observing that object can be invalidated, even if they only care about one property.</p><p>For example, a LocationManager might publish isTracking, lastLocation, and errorMessage. A change to any of them can trigger updates in views observing the manager.</p><p>iOS 17 introduced the Observation framework and @Observable, which makes this tracking more precise. SwiftUI can track <strong>which properties a view actually reads</strong>:</p><pre>import Observation<br><br>@Observable<br>class LocationManager {<br>    var isTracking = false<br>    var lastLocation: CLLocation?<br>    var errorMessage: String?<br>}<br> <br>///A view can read the model through the Environment:<br>struct LocationDisplayView: View {<br>    @Environment(LocationManager.self) var locationManager<br><br>    var body: some View {<br>        Text(&quot;\(locationManager.lastLocation?.coordinate.latitude ?? 0)&quot;)<br>    }<br>}</pre><p>Because this view reads lastLocation, changes to unrelated properties such as errorMessage don’t create the same dependency.</p><p>The migration is relatively straightforward:</p><ul><li>ObservableObject: use @Observable</li><li>@Published: use regular stored properties</li><li>@EnvironmentObject: use @Environment(Type.self)</li><li>@StateObject: use @State when the view owns the observable instance</li></ul><p>There is still an important architectural rule: <strong>@Observable doesn’t mean a view should receive the entire model without thought.</strong> A view becomes dependent on the properties it actually reads, so keeping those dependencies focused still matters.</p><p>In other words <strong>@Observable makes observation more precise, but good view boundaries make those dependencies even more precise.</strong></p><h3>Move State to the Narrowest Possible Scope</h3><p>Where state lives matters. When frequently changing state is owned high in the view hierarchy, its updates can affect a much larger part of the tree than necessary.</p><p>Keep state <strong>as close as possible to the views that actually use it</strong>.</p><p>Instead of keeping tab-specific state in the root:</p><pre>struct ContentView: View {<br>    @State private var selectedTab = 0<br><br>    var body: some View {<br>        TabView(selection: $selectedTab) {<br>            FeedView()<br>            ProfileView()<br>        }<br>    }<br>}<br><br>/// move it into the view that owns that behavior:<br>struct ProfileView: View {<br>    @State private var selectedTab = 0<br><br>    var body: some View {<br>        TabView(selection: $selectedTab) {<br>            // Profile sub-tabs<br>        }<br>    }<br>}</pre><p>Now changes to selectedTab are confined to ProfileView and its subtree instead of involving unrelated content.</p><p>The same principle applies to Environment dependencies. If only MapView needs location data, inject the manager there rather than at the root:</p><pre>TabView {<br>    FeedView()<br><br>    MapView()<br>        .environmentObject(locationManager)<br><br>    SettingsView()<br>}</pre><p>The location dependency now starts at MapView, keeping unrelated parts of the hierarchy outside its affected subtree.</p><p>This is the <strong>push-down principle</strong>:</p><blockquote><strong>State and dependencies should live at the narrowest level that can satisfy their consumers.</strong></blockquote><p>The smaller the affected subtree, the less work SwiftUI has to perform when that state changes.</p><p><strong>Control the scope and frequency of SwiftUI updates</strong>. Keep frequently changing data close to the views that need it, throttle updates before they reach SwiftUI, make important views easy to diff, prefer @Observable for property-level observation, and keep state as local as possible.</p><p>You can find the complete <a href="https://github.com/rajveer-k19/LocationSampler"><strong>Location sample app here</strong></a> and use it to experiment with the patterns we discussed above.</p><p>Until next time, <strong>Ciao.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=051e50db381d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI @Environment: The Overlooked Performance Overhead]]></title>
            <link>https://medium.com/cross-commit/swiftui-environment-the-overlooked-performance-overhead-37307b3b9e7d?source=rss-a769be0a8ae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/37307b3b9e7d</guid>
            <category><![CDATA[environment-swiftui]]></category>
            <category><![CDATA[swiftui-performance]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Rajveer]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 05:04:18 GMT</pubDate>
            <atom:updated>2026-11-12T09:04:47.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*okG-j7Dldr06K7jtnHQJnA.png" /></figure><p>At a <strong>“Meet with Apple”</strong> developer event, an Apple engineer made a statement:</p><blockquote><em>“Writing a value to the Environment doesn’t only affect the views that read the key you’re updating. It updates any view that reads from any Environment key.”</em></blockquote><p>That means a single environment write can trigger checks across the affected view subtree.</p><p>In this post, we’ll look at the difference between a cheap <strong>dependency check</strong> and an actual body re-evaluation, why even skipped updates have a cumulative cost, and the rules to avoid unnecessary environment overhead.</p><h3>Understanding O(n) in a Mobile Context</h3><p><strong>O(n)</strong>, or linear time complexity, simply means that the amount of work grows with the number of items involved.</p><p>In this case, the items are the views in the affected subtree. A smaller subtree means fewer views to check; a larger one means more work. When these checks happen frequently, such as during interactive UI updates, that cost can start to matter.</p><p>Changing an environment value causes SwiftUI to walk through the relevant view subtree and check the views that depend on the environment.</p><h4>The View Hierarchy and Environment Propagation</h4><p>EnvironmentValues are propagated downward through a view hierarchy from parent to child. When you apply an <em>.environment()</em> modifier, the value you set affects the view you modify and all its descendants, until a different environment modifier overrides it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgrcV0TaCvZ0u3XBBI1Dyg.png" /></figure><p>Here is a critical distinction: The Environment is not a true global store; it’s a hierarchical propagation mechanism:</p><ul><li>A view only receives environment values from its ancestors.</li><li>Changes to environment values only propagate to descendants, not to ancestors or siblings.</li><li>As Apple engineers clarified: <em>“This only applies to child views of the </em>.environment<em> modifier that you’re writing with”</em>. If View B applies an environment modifier on View C and View D, only C and D are affected, not View A or View B themselves.</li></ul><h4>The Convenience-Performance Trade-off</h4><p>The Environment solves the problem of passing data through deep view hierarchies without “prop drilling.” You can inject a value at the root and access it five levels deep with a single line of code.</p><p>However, this convenience comes at a cost. Every environment read creates a dependency that must be checked during <em>every</em> environment write.</p><p>The Environment is designed for cross-cutting concerns such as themes, localization, managed object contexts. It is not designed for frequently-changing application state like GPS coordinates, timer values, or scroll offsets.</p><h3>The Anatomy of an Environment Write</h3><h4>The Propagation Traversal</h4><p>When an environment value changes, SwiftUI first needs to determine which views might be affected. It does this by walking down the view hierarchy from the point where the .environment() modifier was applied.</p><p>In Instruments’ Cause and Effect Graph, you’ll typically see two types of environment update nodes:</p><ol><li><strong>External Environment updates</strong>: changes originating outside SwiftUI, such as a system-level colour scheme change when the device switches to Dark Mode.</li><li><strong>EnvironmentWriter updates</strong>: changes made within SwiftUI, such as updating a value through the .environment() modifier.</li></ol><p>The important part is what happens next: SwiftUI doesn’t immediately re-evaluate every view it encounters. It first performs a much cheaper dependency check.</p><h4>The “Mailbox Check” -The Cheap Part</h4><p>For each view in the affected subtree, SwiftUI check:</p><ol><li>Does this view’s body read from the environment?</li><li>If it does, is the environment key that changed one of the keys it reads?</li></ol><p>If the answer is no, SwiftUI can <strong>skip re-evaluating the view’s body</strong>. These appear as <strong>skipped updates</strong> in Instruments.</p><p>Apple describes this behaviour explicitly as:</p><blockquote><em>“The view bodies are only run if the body uses the environment value for the key(s) used in that view and the value changes.”</em></blockquote><p>So if a view reads <em>.name </em>and you change <em>.age</em>, its body doesn’t run because it doesn’t depend on <em>.age</em>.</p><p>W<strong>alking the subtree and checking dependencies is not the same thing as re-evaluating every body</strong>.</p><h4>The “Unpacking” -The Expensive Part</h4><p>If a view does read the environment key that changed, SwiftUI needs to re-evaluate that view’s body.</p><p>Remember that body is a computed property. SwiftUI can evaluate it frequently. But there’s an important performance detail here: even when a view is skipped, SwiftUI still had to visit it and perform the dependency check. Across a large subtree, those small checks can add up.</p><p>Apple’s Instruments guidance highlights exactly this behavior: skipped updates can have a <strong>significant cumulative cost</strong>, even though their associated view bodies never run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVTIsMIbEf7a5-BRWDLj8g.png" /></figure><h4>The Cost of Comparison: Equatable and the Default Value</h4><p>When SwiftUI reaches an environment reader, it compares the old and new values using Equatable to determine if a body re-evaluation is necessary. This comparison itself carries a cost: comparing an Int is a single CPU instruction, whereas comparing a massive Dictionary or a 20-property Struct forces SwiftUI to check every element or property.</p><p>If a value is not Equatable, SwiftUI lacks the information to detect a change. It defensively assumes the value <em>did</em> change, triggering unnecessary re-evaluations.</p><p><strong>Reference types</strong> (Classes) add another layer: they compare by memory address (pointer), not content. Two distinct class instances with identical properties are considered “changed” because their pointers differ.</p><p><strong>The Default Value Trap</strong>: If a view reads an environment key that wasn’t explicitly provided, it falls back to the key’s default. If this default is an unstable reference type (e.g., a computed default returning a new class instance), it appears different across environment passes. This invalidates the view even when the write was for an unrelated key.</p><p>Performance isn’t just about how many body properties run. The dependency checks, value comparisons, and how defaults are provisioned all contribute to the final cost.</p><h3>Three Scenarios for Cost Evaluation</h3><h4>Scenario A: Changing a Value No One Uses</h4><p>What happens when you change an environment value that no view in the subtree actually uses?</p><p>SwiftUI still needs to walk through the affected subtree and perform its <strong>“mailbox check”</strong> on each view. The views can ultimately be skipped, but SwiftUI still has to visit them to determine that they don’t need to update.</p><p>This is visible in Apple’s Instruments demonstrations: even when a view’s body doesn’t execute, the update itself still has an associated cost.</p><p>The important takeaway is that the cost isn’t limited to views whose body is re-evaluated. <strong>Every view that SwiftUI checks contributes to the cost.</strong></p><h4>Scenario B: Changing a Value Used Deep in the Hierarchy</h4><p>Now consider a value that’s actually used by a deeply nested view.</p><p>SwiftUI still traverses the relevant subtree. The root and sibling views perform their dependency checks and are skipped because they don’t depend on the changed key. The deeply nested view that does read that key, however, needs to re-evaluate its body.</p><p>The important distinction is that <strong>a view’s body only runs when the body uses the changed environment key and the value actually changes</strong>.</p><p>You can see this distinction in the Cause and Effect Graph:</p><ul><li>A view that reads the changed environment value shows the environment update followed by execution of its body.</li><li>A view that reads the environment but doesn’t use the specific key that changed still shows the environment update as a cause, but its body isn’t executed. Instruments represents this as a skipped or dimmed update.</li></ul><p>So, a single environment write can contain both kinds of work: <strong>cheap checks for views that can be skipped and more expensive body evaluations for views that actually depend on the changed value.</strong></p><h4>Scenario C: High-Frequency Writes</h4><p>This is where the cost becomes much more noticeable. Suppose you put a frequently changing value such as a timer, GPS coordinate, or scroll offset into the environment. If that value changes 60 times per second, SwiftUI has to perform the propagation and dependency checks 60 times per second.</p><p>The exact numbers will vary with the hierarchy and workload, but the underlying pattern is what matters: <strong>frequent writes multiplied by a large affected subtree can create a substantial amount of unnecessary work.</strong></p><p>Apple explicitly warns against putting frequently updated values, such as geometry values or timers, into the environment for this reason.</p><h4>The “Skipped” Update Cost</h4><p>This is an easy detail to overlook because a skipped view doesn’t execute its body. It can therefore look like SwiftUI did almost no work.</p><p>But the traversal still happened, and every skipped view still required a dependency check. Apple’s WWDC session and related discussions demonstrate that these skipped updates can have a significant cumulative cost.</p><p><strong><em>Environment performance isn’t about how many views re-evaluate. It’s about how many views SwiftUI has to check and how often those checks happen.</em></strong></p><h3>Some Rules of Environment Usage</h3><p>These rules establish the foundation for using the Environment without unnecessarily expanding the cost of propagation.</p><h4>Rule 1: Keep Values Tiny and Specific</h4><p>Avoid putting one large AppState containing dozens of unrelated properties into the environment.</p><p>Instead, split independent pieces of state into <strong>small, specific environment values</strong>.</p><pre>// AVOID: One massive struct<br>struct AppState {<br>    var isLoggedIn: Bool<br>    var preferredColor: Color<br>    var language: String<br>    var lastLocation: CLLocation?<br>    // ... 10 more properties<br>}<br><br>ContentView().environmentObject(AppState())<br><br>// PREFER: Tiny, specific keys<br>ContentView()<br>    .environment(\.isLoggedIn, true)<br>    .environment(\.preferredColor, .blue)<br>    .environment(\.language, &quot;en&quot;)</pre><p>This makes the values themselves simpler to compare and, more importantly, keeps dependencies more focused. A view that only needs .language doesn’t need to depend on unrelated pieces of application state.</p><p><strong><em>Keep environment values small enough that a view only depends on what it actually needs.</em></strong></p><h4>Rule 2: Isolate the View</h4><p>If only a small part of a view needs an environment value, move that dependency into a dedicated child view.</p><p>Consider this example from a Location app:</p><pre>struct ContentView: View {<br>    @EnvironmentObject var locationManager: LocationManager<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Welcome&quot;)<br>            Text(&quot;Lat: \(locationManager.lastLocation?.latitude ?? 0)&quot;)<br>            Text(&quot;Long: \(locationManager.lastLocation?.longitude ?? 0)&quot;)<br>        }<br>    }<br>}</pre><p>Here, ContentView reads locationManager directly, even though only the latitude and longitude display actually needs the location. When the location changes, ContentView becomes one of the views that needs to be considered for the update.</p><p>A better approach is to isolate that dependency:</p><pre>struct ContentView: View {<br>    // ContentView does NOT read location data<br>    var body: some View {<br>        VStack {<br>            Text(&quot;Welcome&quot;)<br>            LocationDisplayView()<br>        }<br>    }<br>}<br><br>struct LocationDisplayView: View {<br>    @EnvironmentObject var locationManager: LocationManager<br><br>    var body: some View {<br>        if let location = locationManager.lastLocation {<br>            Text(&quot;Lat: \(location.coordinate.latitude)&quot;)<br>            Text(&quot;Long: \(location.coordinate.longitude)&quot;)<br>        }<br>    }<br>}</pre><p>Now the environment dependency is scoped to LocationDisplayView. The larger ContentView doesn’t need to re-evaluate its body just because the location changes.</p><p><strong><em>Don’t make a large view listen to a value when only a small part of that view needs it.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h70qE47jswye49kVE3YLlw.png" /></figure><h4>Rule 3: Never Put High-Frequency Data in the Environment</h4><p>The third rule is the most important one for performance-sensitive code: <strong>avoid putting frequently changing data in the Environment.</strong></p><p>GPS coordinates, timer values, scroll offsets, and drag gesture values can change many times during normal interaction. Putting those values high in the environment can turn every update into repeated propagation and dependency checks across a potentially large subtree.</p><p>For example:</p><pre>class LocationManager: ObservableObject {<br>    @Published var currentLocation: CLLocation? // DON&#39;T put this in environment!<br>}</pre><p>A better architecture is to keep the <strong>manager itself</strong> as a stable dependency while scoping the frequently changing data closer to the views that actually need it.</p><p><strong><em>Stable dependencies can live high in the hierarchy. Frequently changing data should stay as close as possible to the views that actually use it.</em></strong></p><p>The important thing to understand is the difference between a <strong>check</strong> and a <strong>re-evaluation</strong>.</p><p>A <em>check</em> is SwiftUI walking through the affected subtree and determining whether a view depends on the environment value that changed. A <em>re-evaluation</em> is when SwiftUI actually calls that view’s body. The second is more expensive, but the first isn’t free either.</p><p><strong><em>Use the Environment for relatively stable, cross-cutting values such as theme, locale, and other shared dependencies. Keep frequently changing data in local state or scoped observation, and throttle updates when appropriate.</em></strong></p><p>The Environment isn’t inherently a performance problem. The problem comes from placing the wrong kind of data in it, especially data that changes frequently and sits high in the view hierarchy.</p><p>We’ll see a little more about Environment in <a href="https://medium.com/@raajveer/swiftui-environment-performance-optimisation-through-smarter-architecture-051e50db381d">Part 2</a>, till then see ya, 👋 .</p><h3>Thanks for reading Cross Commit</h3><p>Before you go:</p><figure><img alt="Follow Cross Commit: practical Swift, Kotlin and mobile AI stories from engineers who ship real apps" src="https://cdn-images-1.medium.com/max/1024/1*aojKTaZmGnisRaGyAL1g0g.png" /><figcaption>Follow Cross Commit on Medium: <a href="https://medium.com/cross-commit">medium.com/cross-commit</a></figcaption></figure><p>👉 <strong>Clap</strong> and <strong>follow</strong> <a href="https://medium.com/u/a769be0a8ae0">Rajveer</a> so their next story lands in your feed 👏</p><p>👉 Want their stories by email? After you follow, tap <strong>Following</strong> on their profile and choose <strong>Email notifications on</strong> 📩</p><p>👉 <strong>Follow </strong><a href="https://medium.com/cross-commit"><strong>Cross Commit</strong></a> for practical iOS, Android and mobile AI stories from engineers who ship real apps</p><p>👉 Writing about Swift, Kotlin or mobile AI? Cross Commit is open to writers worldwide. Leave a response below and we’ll get in touch ✍️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37307b3b9e7d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cross-commit/swiftui-environment-the-overlooked-performance-overhead-37307b3b9e7d">SwiftUI @Environment: The Overlooked Performance Overhead</a> was originally published in <a href="https://medium.com/cross-commit">Cross Commit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Cost of ObservableObject in SwiftUI]]></title>
            <link>https://medium.com/@raajveer/the-hidden-cost-of-observableobject-in-swiftui-4c23c7ddc513?source=rss-a769be0a8ae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c23c7ddc513</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swiftui-performance]]></category>
            <category><![CDATA[observableobject]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swiftui-body-reevaluation]]></category>
            <dc:creator><![CDATA[Rajveer]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 07:06:01 GMT</pubDate>
            <atom:updated>2026-08-17T07:06:01.767Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kjDZ4406zMEyJjDX1j00Yw.png" /></figure><p>I once ran into a strange SwiftUI performance issue: a single timer updating remainingTime every second was making my entire dashboard 10 subviews, getting refreshed for no reason.</p><p>The culprit? ObservableObject and its <strong>object-level invalidation</strong>. God, it was nasty to debug.</p><p>With @Published, a change to any published property triggers <em>objectWillChange</em>, potentially causing <strong>all views observing that object to re-evaluate their body</strong>, even when they don’t depend on the changed property.</p><p>In this article, we’ll measure that cost, understand how SwiftUI tracks dependencies, and see how @Observable can help reduce unnecessary re-evaluation.</p><h3>The “Broadcast Effect”: Object-Level Invalidation</h3><p>When a class conforms to ObservableObject and uses @Published, SwiftUI observes the <strong>entire object</strong>, not individual properties. The object exposes a single <em>objectWillChange</em> publisher, which fires whenever any published property is about to change.</p><p>Consider a typical view model:</p><pre>class DashboardViewModel: ObservableObject {<br>    @Published var currentRound: Int = 1<br>    @Published var remainingTime: TimeInterval = 0<br>    @Published var totalRounds: Int = 12<br>    @Published var playerScore: Int = 0<br>    @Published var gameStatus: String = &quot;Ready&quot;<br>}</pre><p>If remainingTime updates 60 times per second, <strong>every view observing DashboardViewModel can have its body re-evaluated 60 times per second</strong> including views that only display totalRounds or playerScore.</p><p>That’s the <strong>broadcast effect</strong>: one property changes, but every observer pays the cost of re-evaluation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHdiMV7wj5zNGpq9ao7J1w.png" /></figure><p>In a dashboard with 15 published properties and 20 observing subviews, updating a single timestamp can cause all 20 subviews to recompute their body, even though most don’t use that timestamp. At higher update frequencies, those unnecessary computations can contribute to dropped frames, especially during animations.</p><h4>Push vs. Pull Tracking</h4><p>ObservableObject uses <strong>push-based notification</strong>. The object broadcasts a change to all subscribers without knowing which property each view actually depends on. The view receives the notification and re-evaluates its body to determine whether the change matters.</p><p>This differs from <strong>pull-based tracking</strong>, where the system tracks which properties a view actually reads and can invalidate only the views that depend on those properties. This distinction becomes important when we look at @Observable.</p><h3>Coalescing Helps, But Doesn’t Solve the Problem</h3><p>SwiftUI does coalesce multiple <em>objectWillChange</em> notifications within the same update cycle, so a view’s body isn’t recomputed once for every individual notification.</p><p>But coalescing doesn’t remove the underlying broadcast effect. <strong>All observing views can still be re-evaluated during that cycle.</strong></p><p>The real cost is therefore driven by the number of <strong>observing views × update cycles</strong>, rather than simply the number of properties that changed.</p><h3>Inside SwiftUI’s Dependency Tracking Mechanism</h3><p>When a view uses @ObservedObject or @StateObject, SwiftUI subscribes to the ObservableObject’s <em>objectWillChange</em> publisher. This subscription is <strong>instance-level</strong>, not property-level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EaqkAW6RwhY8r7Wgz1dFfg.png" /></figure><p>That means SwiftUI knows that the view depends on the object, but not necessarily which properties it actually reads. A view that only displays totalRounds can still be invalidated when remainingTime changes.</p><p>You can see this behaviour using Self._printChanges() inside the view’s body. It can reveal invalidation events even when the view doesn’t read the property that changed.</p><h4>From Object-Level to Property-Level Tracking</h4><p>With ObservableObject, dependency tracking is relatively <strong>coarse-grained</strong> because the view subscribes to the object’s publisher.</p><p>The @Observable macro, introduced in Swift 5.9, takes a more granular approach. When a view reads a property from an @Observable type during body evaluation, SwiftUI can track that <strong>specific property access</strong>. When that property changes, SwiftUI can invalidate the views that actually depend on it.</p><p>This difference is central to understanding why @Observable can reduce unnecessary body re-evaluation.</p><h4>Measuring Body Re-evaluation</h4><p>To see how often your views are being re-evaluated, SwiftUI provides several useful debugging techniques.</p><p><strong>1. Self._printChanges()</strong></p><p>Place it inside body:</p><pre>var body: some View {<br>    let _ = Self._printChanges()<br>    Text(&quot;Hello, world!&quot;)<br>}</pre><p>The console shows what caused the view to be invalidated, making it useful for validating your dependency assumptions.</p><p><strong>2. Random Background Colours</strong></p><p>Give a view a randomly generated background colour. If the colour changes frequently, the view’s body is being re-evaluated.</p><p><strong>3. Instruments</strong></p><p>Use Instruments’ SwiftUI profiling tools to measure view invalidations and identify areas where unnecessary re-evaluation may be affecting performance.</p><h3>Property-Level Tracking with @Observable (iOS 17+)</h3><p>At WWDC23, Apple introduced the Observation framework and @Observable macro, changing how SwiftUI tracks state dependencies.</p><p>Instead of relying on ObservableObject and @Published, @Observable lets SwiftUI track the <strong>properties a view actually reads</strong>.</p><pre>@Observable<br>class TimerManager {<br>    var currentRound: Int = 1<br>    var remainingTime: TimeInterval = 0<br>    var totalRounds: Int = 12<br>}</pre><p>There are no @Published properties or ObservableObject conformance. The macro transforms the type at compile time to support observation.</p><h4>The Granularity Advantage</h4><p>When a view’s body reads totalRounds, SwiftUI tracks that specific property. If remainingTime changes, the view doesn’t need to re-evaluate because it doesn’t depend on it.</p><p>This <strong>property-level tracking</strong> can significantly reduce unnecessary body evaluations, especially in UIs with frequent updates, deep navigation, or large object graphs.</p><p>Apple demonstrates this behavior in its <a href="https://developer.apple.com/videos/play/wwdc2023/10149/">WWDC23 “Discover Observation in SwiftUI” session</a>: a view that reads donuts is invalidated when donuts changes, but remains unaffected when an unrelated property such as order changes.</p><p>In real-world applications, this can make a noticeable difference in responsiveness by limiting updates to the views that actually depend on the changed data.</p><p>The migration can also simplify the codebase by removing @Published, @StateObject, and @ObservedObject in many cases.</p><h3>Optimisation Strategies for iOS 16 and Below</h3><p>Not every app can move to iOS 17 immediately. If you’re still supporting earlier versions, you can reduce the ObservableObject performance cost with a few practical strategies.</p><h4>Split Large Objects into Focused Models</h4><p>Instead of one large ObservableObject containing unrelated state, split it into smaller models that represent specific concerns.</p><pre>// Instead of:<br>class AppState: ObservableObject {<br>    @Published var user: User<br>    @Published var settings: Settings<br>    @Published var notifications: [Notification]<br>}<br><br>// Do:<br>class UserState: ObservableObject {<br>    @Published var user: User<br>}<br><br>class SettingsState: ObservableObject {<br>    @Published var settings: Settings<br>}<br><br>class NotificationState: ObservableObject {<br>    @Published var notifications: [Notification]<br>}</pre><p>This reduces the <strong>blast radius</strong> of changes. A view observing UserState won’t be invalidated when SettingsState changes.</p><h4>Pass Values Instead of Entire Objects</h4><p>If a child view only needs one value, pass that value or a Binding, instead of passing the entire observable object.</p><pre>struct OrderHeader: View {<br>    let orderTotal: Decimal<br><br>    var body: some View {<br>        Text(&quot;Total: \(orderTotal)&quot;)<br>    }<br>}</pre><p>The child no longer depends on the observable object, so changes elsewhere in that object won’t invalidate it.</p><h4>Use Equatable Where Appropriate</h4><p>For views whose inputs can be meaningfully compared, Equatable can help SwiftUI avoid unnecessary updates.</p><pre>struct MyView: View, Equatable {<br>    let value: String<br><br>    var body: some View {<br>        Text(value)<br>    }<br>}<br><br>/// You can then use EquatableView when appropriate:<br><br>EquatableView(content: MyView(value: &quot;Hello&quot;))</pre><p>This can be useful when a view receives data that SwiftUI cannot otherwise efficiently compare.</p><h4>Get Object Ownership Right</h4><p>Use the correct property wrapper based on who owns the observable object:</p><ul><li><strong>@StateObject</strong>: The view creates and owns the object.</li><li><strong>@ObservedObject</strong>: The view receives an object owned elsewhere.</li></ul><p>Getting this wrong can lead to unnecessary object creation and additional work during view updates. In large navigation hierarchies, correct ownership becomes especially important.</p><h3>Migration Tips: Moving from ObservableObject to @Observable</h3><p>For iOS 17+ and macOS 14+, the migration is mostly a syntax cleanup:</p><ul><li>Replace ObservableObject with @Observable.</li><li>Remove @Published from properties.</li><li>Replace @StateObject with @State.</li><li>Replace @ObservedObject with a plain property.</li><li>Replace @EnvironmentObject with @Environment(MyModel.self).</li><li>For side effects previously driven by <em>objectWillChange</em>, use observation tools such as withObservationTracking.</li><li>If supporting iOS 16 and iOS 17+, use #available and keep ObservableObject as the fallback.</li></ul><p>Apple continues to support ObservableObject, but for new iOS 17+ code, @Observable provides more granular observation with less boilerplate.</p><p>If you’re seeing unexpected re-evaluations, start with Self._printChanges(), measure the problem, and then consider whether your observation model needs a rethink.</p><p>In large SwiftUI apps, <strong>how you observe state can matter just as much as the state itself.</strong></p><p>Ciao for now, SwiftUI folks. Keep building, keep exploring, and I’ll see you in the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c23c7ddc513" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>