<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>SwiftUI &#8211; swiftyplace</title>
	<atom:link href="https://www.swiftyplace.com/swiftui/feed" rel="self" type="application/rss+xml" />
	<link>https://www.swiftyplace.com</link>
	<description>Learn how to build amazing apps with SwiftUI and Combine</description>
	<lastBuildDate>Thu, 05 Nov 2026 14:50:25 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.5</generator>

<image>
	<url>https://www.swiftyplace.com/wp-content/uploads/2023/08/cropped-logo-1-32x32.png</url>
	<title>SwiftUI &#8211; swiftyplace</title>
	<link>https://www.swiftyplace.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Dependency Injection in SwiftUI: Initializer, Environment, or Container</title>
		<link>https://www.swiftyplace.com/blog/dependency-injection-swiftui?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=dependency-injection-swiftui</link>
					<comments>https://www.swiftyplace.com/blog/dependency-injection-swiftui#respond</comments>
		
		<dc:creator><![CDATA[Karin Prater]]></dc:creator>
		<pubDate>Thu, 05 Nov 2026 14:49:41 +0000</pubDate>
				<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Architecture]]></category>
		<guid isPermaLink="false">https://www.swiftyplace.com/?p=1005797</guid>

					<description><![CDATA[<p>Where does a SwiftUI view get its dependencies from? Compare the initializer, the environment, and dependency injection containers like Factory, with the trade-offs of each.</p>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/dependency-injection-swiftui">Dependency Injection in SwiftUI: Initializer, Environment, or Container</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Dependency injection means the view model gets its dependencies from outside, and whoever creates the view model decides which service to pass.  In SwiftUI, that &#8220;whoever&#8221; is usually a view. So where does the view get the service from, and how can a preview give it a mock instead?</p>



<p class="wp-block-paragraph">In this post, I&#8217;ll show how dependency injection in SwiftUI works as an app grows, with one example that goes from a single screen to a full app. Passing the service through the view&#8217;s initializer works for a single screen, but breaks down once the screen is used inside other views. That&#8217;s why I put services into the SwiftUI environment, which also makes previews and UI tests easier.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Starting Simple: Passing the Service Through the View&#8217;s Initializer</h2>



<p class="wp-block-paragraph">First, the setup. It&#8217;s the same as in Dependency Injection in Swift: a protocol for the service, a live implementation, a mock, and a view model that gets the service through its initializer. You can read how to set this up in more detail in this <a href="https://www.swiftyplace.com/blog/dependency-injection-swift">blog post</a>.</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>nonisolated protocol ProductService: Sendable {
    func fetchProducts() async throws -> &#91;Product&#93;
}

nonisolated struct LiveProductService: ProductService {
    @concurrent
    func fetchProducts() async throws -> &#91;Product&#93; { /* request, decode */ }
}

nonisolated struct MockProductService: ProductService {
    var products: &#91;Product&#93; = []

    func fetchProducts() async throws -> &#91;Product&#93; { products }
}

@MainActor
@Observable
final class ProductViewModel {
    private(set) var state: LoadingState&lt;&#91;Product&#93;> = .idle
    private let productService: ProductService

    init(productService: ProductService) {
        self.productService = productService
    }

    func load() async {
        state = .loading
        do {
            state = .loaded(try await productService.fetchProducts())
        } catch {
            state = .failed("Couldn't load products.")
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">nonisolated</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">protocol</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ProductService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Sendable </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">fetchProducts</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">throws</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> &#91;Product&#93;</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">nonisolated</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">LiveProductService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">ProductService </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@concurrent</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">fetchProducts</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">throws</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> &#91;Product&#93; { </span><span style="color: #7B7F8B">/* request, decode */</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">nonisolated</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">MockProductService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">ProductService </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> products: &#91;Product&#93; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">fetchProducts</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">throws</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> &#91;Product&#93; { products }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> state: LoadingState&lt;&#91;Product&#93;&gt; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .idle</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> productService: ProductService</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">productService</span><span style="color: #F6F6F4">: ProductService) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.productService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> productService</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">load</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        state </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .loading</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">do</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            state </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .</span><span style="color: #97E1F1">loaded</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> productService.</span><span style="color: #97E1F1">fetchProducts</span><span style="color: #F6F6F4">())</span></span>
<span class="line"><span style="color: #F6F6F4">        } </span><span style="color: #F286C4">catch</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            state </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .</span><span style="color: #97E1F1">failed</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Couldn&#39;t load products.</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">We start with a single screen that shows the products. The view creates its view model in <code>@State</code>, and the service is written right there:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ProductsScreen: View {
    @State private var viewModel = ProductViewModel(productService: LiveProductService())

    var body: some View {
        ProductListView(state: viewModel.state)
            .task { await viewModel.load() }
    }
}

#Preview {
    ProductsScreen() // calls the real API
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ProductsScreen</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">productService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">LiveProductService</span><span style="color: #F6F6F4">())</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">ProductListView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">state</span><span style="color: #F6F6F4">: viewModel.state)</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">task</span><span style="color: #F6F6F4"> { </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> viewModel.</span><span style="color: #97E1F1">load</span><span style="color: #F6F6F4">() }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">ProductsScreen</span><span style="color: #F6F6F4">() </span><span style="color: #7B7F8B">// calls the real API</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The view model itself is fine: it takes a protocol in its initializer. But the view hard-codes which service to pass, so the preview always calls the real API. Without a network connection, it shows an error; with a slow one, a spinner.</p>



<p class="wp-block-paragraph">The fix is the same idea one level up: the view gets the service through its own initializer. The live service is the default, so nothing changes for the rest of the app:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);--cbp-line-highlight-color:rgba(251, 251, 239, 0.2);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ProductsScreen: View {
    @State private var viewModel: ProductViewModel

    init(productService: ProductService = LiveProductService()) {
        _viewModel = State(initialValue: ProductViewModel(productService: productService))
    }

    var body: some View {
        ProductListView(state: viewModel.state)
            .task { await viewModel.load() }
    }
}

#Preview {
    ProductsScreen(productService: MockProductService(products: Product.samples))
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ProductsScreen</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> viewModel: ProductViewModel</span></span>
<span class="line"></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">productService</span><span style="color: #F6F6F4">: ProductService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">LiveProductService</span><span style="color: #F6F6F4">()) {</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">        _viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">State</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">initialValue</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">productService</span><span style="color: #F6F6F4">: productService))</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">ProductListView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">state</span><span style="color: #F6F6F4">: viewModel.state)</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">task</span><span style="color: #F6F6F4"> { </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> viewModel.</span><span style="color: #97E1F1">load</span><span style="color: #F6F6F4">() }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4"> {</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">ProductsScreen</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">productService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">MockProductService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">products</span><span style="color: #F6F6F4">: Product.samples))</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<ul class="wp-block-list">
<li><strong>The app keeps calling <code>ProductsScreen()</code>.</strong> Only the preview passes the mock.</li>



<li><strong><code>_viewModel = State(initialValue:)</code></strong> sets the initial value of the <code>@State</code> property from inside <code>init</code>. The underscore accesses the property wrapper itself instead of the wrapped value.</li>



<li><strong>The initial value is only used the first time.</strong> SwiftUI keeps the first view model for as long as the view is on screen. If the parent later re-creates <code>ProductsScreen</code> with a different service, the new one is ignored.</li>



<li><strong>Keep the view model&#8217;s <code>init</code> cheap.</strong> Every time the parent re-creates the <code>ProductsScreen</code> struct, this <code>init</code> runs and creates a new <code>ProductViewModel</code>, which SwiftUI then throws away. That&#8217;s fine as long as the initializer only stores its dependencies and doesn&#8217;t start any work.</li>
</ul>



<p class="wp-block-paragraph">This works as long as the screen is only previewed on its own. As you&#8217;ll see next, it breaks down as soon as the screen is used inside other views.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Why Initializer Injection Breaks Down as the App Grows</h2>



<p class="wp-block-paragraph">Now the app grows. <code>ProductsScreen</code> becomes one tab in a <code>RootTabView</code>, next to a <code>FavoritesScreen</code> that works the same way:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct RootTabView: View {
    var body: some View {
        TabView {
            Tab("Products", systemImage: "bag") {
                ProductsScreen()      // default: live service
            }
            Tab("Favorites", systemImage: "heart") {
                FavoritesScreen()     // default: live service
            }
        }
    }
}

#Preview {
    RootTabView() // both tabs use the real API and the real UserDefaults
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">RootTabView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">TabView</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Tab</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Products</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">systemImage</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">bag</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">ProductsScreen</span><span style="color: #F6F6F4">()      </span><span style="color: #7B7F8B">// default: live service</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Tab</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Favorites</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">systemImage</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">heart</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">FavoritesScreen</span><span style="color: #F6F6F4">()     </span><span style="color: #7B7F8B">// default: live service</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">RootTabView</span><span style="color: #F6F6F4">() </span><span style="color: #7B7F8B">// both tabs use the real API and the real UserDefaults</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The preview of <code>ProductsScreen</code> still works, because it passes the mock itself. But the preview of <code>RootTabView</code> creates both screens with their defaults, the live services. There&#8217;s no way to reach in and change that from the outside.</p>



<p class="wp-block-paragraph">With initializer injection, the only fix is to pass the services through the parent:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);--cbp-line-highlight-color:rgba(251, 251, 239, 0.2);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct RootTabView: View {
    let productService: ProductService     // not used here, only passed on
    let favoritesService: FavoritesService // not used here, only passed on

    var body: some View {
        TabView {
            Tab("Products", systemImage: "bag") {
                ProductsScreen(productService: productService)
            }
            Tab("Favorites", systemImage: "heart") {
                FavoritesScreen(favoritesService: favoritesService)
            }
        }
    }
}

#Preview {
    RootTabView(
        productService: MockProductService(products: Product.samples),
        favoritesService: MockFavoritesService()
    )
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">RootTabView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> productService: ProductService     </span><span style="color: #7B7F8B">// not used here, only passed on</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> favoritesService: FavoritesService </span><span style="color: #7B7F8B">// not used here, only passed on</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">TabView</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Tab</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Products</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">systemImage</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">bag</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">ProductsScreen</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">productService</span><span style="color: #F6F6F4">: productService)</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Tab</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Favorites</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">systemImage</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">heart</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">FavoritesScreen</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">favoritesService</span><span style="color: #F6F6F4">: favoritesService)</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">RootTabView</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">productService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">MockProductService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">products</span><span style="color: #F6F6F4">: Product.samples),</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">favoritesService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">MockFavoritesService</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    )</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">This works for one level. Here&#8217;s how it gets worse as the app grows:</p>



<ul class="wp-block-list">
<li><strong><code>RootTabView</code> takes dependencies it doesn&#8217;t use.</strong> It only has the services so it can pass them to its children.</li>



<li><strong>Every new level adds the same parameters.</strong> If <code>ProductsScreen</code> shows a <code>ProductDetailScreen</code> with its own view model, <code>ProductsScreen</code> also needs to pass the service on, even though its own view model already has one.</li>



<li><strong>Every new service adds a parameter to every view in the chain.</strong> Add a cart service, and <code>RootTabView</code>, <code>ProductsScreen</code>, and every view in between get another parameter.</li>



<li><strong>Every view above needs this to be previewable.</strong> If one view in the chain uses the default instead of passing the service on, every preview above it calls the real API again.</li>
</ul>



<p class="wp-block-paragraph">That&#8217;s why I don&#8217;t pass services through view initializers. <strong>I prefer to put them into the environment.</strong></p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">The Solution: Services in the SwiftUI Environment</h2>



<p class="wp-block-paragraph">The environment solves exactly the problem from the previous section. A value set on a view reaches every view below it, and none of the views in between need to know about it.</p>


<div class="gb-container gb-container-5378eee7">

<figure class="gb-block-image gb-block-image-9def0a71"><img fetchpriority="high" decoding="async" width="911" height="518" class="gb-image gb-image-9def0a71" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swiftui-1.webp" alt="dependency injection in swiftui direct through view init or environment" title="dependency-injection-swiftui-1" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swiftui-1.webp 911w, https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swiftui-1-300x171.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swiftui-1-768x437.webp 768w" sizes="(max-width: 911px) 100vw, 911px" /></figure>

</div>


<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Put the service into the environment</h3>



<p class="wp-block-paragraph">With the <code>@Entry</code> macro, this is one line per service in an extension on <code>EnvironmentValues</code>:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>extension EnvironmentValues {
    @Entry var productService: ProductService = LiveProductService()
    @Entry var favoritesService: FavoritesService = LiveFavoritesService()
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">extension</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">EnvironmentValues</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Entry</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> productService: ProductService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">LiveProductService</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Entry</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> favoritesService: FavoritesService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">LiveFavoritesService</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<ul class="wp-block-list">
<li><strong>The type is the protocol.</strong> If it were <code>LiveProductService</code>, you couldn&#8217;t put a mock in its place.</li>



<li><strong>The default is the live service.</strong> If nobody sets a value, every view gets the live service, so the app works without any setup at the root.</li>



<li><strong>A live default is safe here</strong> because the services are stateless <code>nonisolated</code> <code>Sendable</code> structs. Without an injected value, SwiftUI may create the default more than once, and for a stateless service, extra copies change nothing.</li>
</ul>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Read it and create the view model</h3>



<p class="wp-block-paragraph">The screen reads the service with <code>@Environment</code>. The environment isn&#8217;t available yet when the view&#8217;s <code>init</code> runs, so the view model can&#8217;t be created there anymore. Instead, it&#8217;s an optional and gets created in <code>.task</code>:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);--cbp-line-highlight-color:rgba(251, 251, 239, 0.2);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ProductsScreen: View {
    @Environment(.productService) private var productService
    @State private var viewModel: ProductViewModel?

    var body: some View {
        Group {
            if let viewModel {
                ProductListView(state: viewModel.state)
            } else {
                ProgressView()
            }
        }
        .task {
            if viewModel == nil {
                viewModel = ProductViewModel(productService: productService)
            }
            await viewModel?.load()
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ProductsScreen</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Environment</span><span style="color: #F6F6F4">(.productService) </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> productService</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> viewModel: ProductViewModel</span><span style="color: #F286C4">?</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Group</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> viewModel {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">ProductListView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">state</span><span style="color: #F6F6F4">: viewModel.state)</span></span>
<span class="line"><span style="color: #F6F6F4">            } </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">ProgressView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">task</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">nil</span><span style="color: #F6F6F4"> {</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">                viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">productService</span><span style="color: #F6F6F4">: productService)</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> viewModel</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">load</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<ul class="wp-block-list">
<li><strong><code>.task</code> runs every time the view appears</strong>, for example when the user switches back to this tab. The <code>if viewModel == nil</code> check makes sure the view model is only created the first time.</li>



<li><strong>The view model is created exactly once.</strong> </li>
</ul>



<p class="wp-block-paragraph"><code>RootTabView</code> goes back to having no parameters at all:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct RootTabView: View {
    var body: some View {
        TabView {
            Tab("Products", systemImage: "bag") {
                ProductsScreen()
            }
            Tab("Favorites", systemImage: "heart") {
                FavoritesScreen()
            }
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">RootTabView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">TabView</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Tab</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Products</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">systemImage</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">bag</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">ProductsScreen</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Tab</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Favorites</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">systemImage</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">heart</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">FavoritesScreen</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Override it where you need a different service</h3>



<p class="wp-block-paragraph">Now one modifier on any view replaces the service for everything below it:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>#Preview("Root") {
    RootTabView()
        .environment(.productService, MockProductService(products: Product.samples))
        .environment(.favoritesService, MockFavoritesService())
}

#Preview("Products") {
    ProductsScreen()
        .environment(.productService, MockProductService(products: Product.samples))
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Root</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">RootTabView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">environment</span><span style="color: #F6F6F4">(.productService, </span><span style="color: #97E1F1">MockProductService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">products</span><span style="color: #F6F6F4">: Product.samples))</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">environment</span><span style="color: #F6F6F4">(.favoritesService, </span><span style="color: #97E1F1">MockFavoritesService</span><span style="color: #F6F6F4">())</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Products</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">ProductsScreen</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">environment</span><span style="color: #F6F6F4">(.productService, </span><span style="color: #97E1F1">MockProductService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">products</span><span style="color: #F6F6F4">: Product.samples))</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">It doesn&#8217;t matter how deep <code>ProductsScreen</code> sits in the hierarchy. The override on the parent preview reaches it. You only set it on the views that need a different service: in previews, or on one part of the app that should use another service.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Variant: keep the view model non-optional</h3>



<p class="wp-block-paragraph">If you don&#8217;t want the optional view model, there&#8217;s a middle way. <code>ProductsScreen</code> keeps its initializer from the first example, and the view that shows it reads the environment and passes the service in:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct RootTabView: View {
    @Environment(.productService) private var productService
    @Environment(.favoritesService) private var favoritesService

    var body: some View {
        TabView {
            Tab("Products", systemImage: "bag") {
                ProductsScreen(productService: productService)
            }
            Tab("Favorites", systemImage: "heart") {
                FavoritesScreen(favoritesService: favoritesService)
            }
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">RootTabView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Environment</span><span style="color: #F6F6F4">(.productService) </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> productService</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Environment</span><span style="color: #F6F6F4">(.favoritesService) </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> favoritesService</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">TabView</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Tab</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Products</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">systemImage</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">bag</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">ProductsScreen</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">productService</span><span style="color: #F6F6F4">: productService)</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Tab</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Favorites</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">systemImage</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">heart</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">FavoritesScreen</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">favoritesService</span><span style="color: #F6F6F4">: favoritesService)</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<ul class="wp-block-list">
<li><code>ProductsScreen</code> stays as simple as in the first example, with a non-optional view model.</li>



<li>Only the parent touches the environment, and an override on its preview still reaches both tabs.</li>



<li>The caveats from the first example come back: the initial value is only used the first time, and the view model&#8217;s <code>init</code> must stay cheap.</li>
</ul>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Why This Matters for UI Tests</h2>



<p class="wp-block-paragraph">The same property pays off again in UI tests. A UI test runs the app in a separate process, so it can&#8217;t pass a mock into a view. All it can do is launch the app with arguments.</p>



<p class="wp-block-paragraph">With initializer injection, the app would have to pass the mock down every chain of views to every screen. With the environment, the app reads the argument and sets the mock once, wherever it should apply. Here it&#8217;s set at the root, for the whole app:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@main
struct ShopApp: App {
    private let productService: ProductService

    init() {
        if ProcessInfo.processInfo.arguments.contains("-uiTesting") {
            productService = MockProductService(products: Product.samples)
        } else {
            productService = LiveProductService()
        }
    }

    var body: some Scene {
        WindowGroup {
            RootTabView()
                .environment(.productService, productService)
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@main</span></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ShopApp</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">App </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> productService: ProductService</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">() {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> ProcessInfo.processInfo.arguments.</span><span style="color: #97E1F1">contains</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">-uiTesting</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">            productService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">MockProductService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">products</span><span style="color: #F6F6F4">: Product.samples)</span></span>
<span class="line"><span style="color: #F6F6F4">        } </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            productService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">LiveProductService</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> Scene {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">WindowGroup</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">RootTabView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">                .</span><span style="color: #97E1F1">environment</span><span style="color: #F6F6F4">(.productService, productService)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Every screen in the app picks up the mock, and none of them knows it&#8217;s running in a UI test. How the test passes the launch argument, and how to set up different scenarios, is the topic of UI Testing SwiftUI Apps With Mock Services.</p>



<p class="wp-block-paragraph">If only one feature should use the mock, set the same <code>.environment</code> on that feature&#8217;s view instead, like the products tab. Everything in that branch gets the mock, and the rest of the app keeps the live service.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Keeping Previews Safe</h2>



<p class="wp-block-paragraph">The live default has one downside. If a preview forgets the override, nothing tells you: the preview uses the live service and calls the real API. With one service that&#8217;s easy to remember. With several, every preview has to override every one of them.</p>



<p class="wp-block-paragraph">A small view extension collects all mocks in one place:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>extension View {
    func injectMockServices() -> some View {
        self
            .environment(.productService, MockProductService(products: Product.samples))
            .environment(.favoritesService, MockFavoritesService())
    }
}

#Preview {
    RootTabView()
        .injectMockServices()
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">extension</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">View</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">injectMockServices</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">environment</span><span style="color: #F6F6F4">(.productService, </span><span style="color: #97E1F1">MockProductService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">products</span><span style="color: #F6F6F4">: Product.samples))</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">environment</span><span style="color: #F6F6F4">(.favoritesService, </span><span style="color: #97E1F1">MockFavoritesService</span><span style="color: #F6F6F4">())</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">RootTabView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">injectMockServices</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">When you add a new service, you add its mock here once, and every preview that uses <code>injectMockServices()</code> gets it.</p>



<p class="wp-block-paragraph">To use a live service for one preview and mocks for everything else, set the specific value before the modifier:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>#Preview("Real Product API") {
    RootTabView()
        .environment(.productService, LiveProductService()) // must come before injectMockServices()
        .injectMockServices()
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Real Product API</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">RootTabView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">environment</span><span style="color: #F6F6F4">(.productService, </span><span style="color: #97E1F1">LiveProductService</span><span style="color: #F6F6F4">()) </span><span style="color: #7B7F8B">// must come before injectMockServices()</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">injectMockServices</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The order matters because environment values set closer to the view win. The <code>.environment</code> call directly on <code>RootTabView</code> is applied innermost, so it overrides the value that <code>injectMockServices()</code> sets further out.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">The Alternative: DI Containers Like Factory</h2>



<p class="wp-block-paragraph">The environment works, but it has a cost. Every screen now has an <code>@Environment</code> property, an optional <code>@State</code> view model, a <code>.task</code> that creates it, and a <code>nil</code> case to handle. With a handful of screens, that&#8217;s fine. With many, it&#8217;s the same few lines over and over. That&#8217;s usually why people reach for a DI container. One of the most popular one in Swift is <a href="https://github.com/hmlongco/Factory" data-type="link" data-id="https://github.com/hmlongco/Factory" target="_blank" rel="noopener">Factory</a>.</p>



<p class="wp-block-paragraph">Another option is Point-Free&#8217;s <a href="https://github.com/pointfreeco/swift-dependencies" data-type="link" data-id="https://github.com/pointfreeco/swift-dependencies" target="_blank" rel="noopener">swift-dependencies</a>, which takes a similar approach with a <code>@Dependency</code> property wrapper, and is built around task-local values from the start.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h4 class="wp-block-heading">What Factory automates</h4>



<p class="wp-block-paragraph">Each dependency is registered once, in an extension on Factory&#8217;s <code>Container</code>. The view model then resolves it with the <code>@Injected</code> property wrapper:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);--cbp-line-highlight-color:rgba(251, 251, 239, 0.2);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import Factory

extension Container {
    var productService: Factory&lt;ProductService> {
        self { LiveProductService() }
    }
}

@MainActor
@Observable
final class ProductViewModel {
    @ObservationIgnored
    @Injected(.productService) private var productService

    private(set) var state: LoadingState&lt;&#91;Product&#93;> = .idle

    func load() async { /* ... */ }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">import</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Factory</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">extension</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Container</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> productService: Factory&lt;ProductService&gt; {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">LiveProductService</span><span style="color: #F6F6F4">() }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@ObservationIgnored</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Injected</span><span style="color: #F6F6F4">(.productService) </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> productService</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> state: LoadingState&lt;&#91;Product&#93;&gt; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .idle</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">load</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> { </span><span style="color: #7B7F8B">/* ... */</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h4 class="wp-block-heading">The main win: a simpler view</h4>



<p class="wp-block-paragraph">Compare the screen with the environment version from above. With Factory, the view model gets its service on its own, so the view just creates it:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ProductsScreen: View {
    @State private var viewModel = ProductViewModel()

    var body: some View {
        ProductListView(state: viewModel.state)
            .task { await viewModel.load() }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ProductsScreen</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4">()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">ProductListView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">state</span><span style="color: #F6F6F4">: viewModel.state)</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">task</span><span style="color: #F6F6F4"> { </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> viewModel.</span><span style="color: #97E1F1">load</span><span style="color: #F6F6F4">() }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">No <code>@Environment</code> property, no optional view model, no <code>nil</code> case, and no creating the view model in <code>.task</code>. And that&#8217;s on every screen.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h4 class="wp-block-heading">Overrides for previews</h4>



<p class="wp-block-paragraph">Instead of <code>.environment</code> overrides, you register a different version. Here are the same examples as above, with Factory.</p>



<p class="wp-block-paragraph">The parent preview:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>#Preview {
    let _ = Container.shared.productService.register {
        MockProductService(products: Product.samples)
    }
    RootTabView()
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">_</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> Container.shared.productService.</span><span style="color: #97E1F1">register</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">MockProductService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">products</span><span style="color: #F6F6F4">: Product.samples)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">RootTabView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h4 class="wp-block-heading">Resolving the whole dependency graph</h4>



<p class="wp-block-paragraph">The bigger benefit shows up when dependencies depend on each other. The view model needs a product service, the service needs an <code>APIClient</code>, and the <code>APIClient</code> needs the token store that holds the current auth token. Without a container, someone has to create all of these in the right order and pass each one into the next.</p>



<p class="wp-block-paragraph">With Factory, each dependency is registered once, together with what it needs:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>extension Container {
    var tokenStore: Factory&lt;TokenStore> {
        self { LiveTokenStore() }.singleton
    }

    var apiClient: Factory&lt;APIClient> {
        self { APIClient(tokenStore: self.tokenStore()) }
    }

    var productService: Factory&lt;ProductService> {
        self { LiveProductService(apiClient: self.apiClient()) }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">extension</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Container</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> tokenStore: Factory&lt;TokenStore&gt; {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">LiveTokenStore</span><span style="color: #F6F6F4">() }.singleton</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> apiClient: Factory&lt;APIClient&gt; {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">APIClient</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">tokenStore</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">tokenStore</span><span style="color: #F6F6F4">()) }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> productService: Factory&lt;ProductService&gt; {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">LiveProductService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">apiClient</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">apiClient</span><span style="color: #F6F6F4">()) }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">When the view model asks for <code>productService</code>, Factory resolves the whole chain. <code>.singleton</code> makes sure the whole app shares one token store. How to build the same graph without a framework is the topic of Building the Dependency Graph in SwiftUI.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h4 class="wp-block-heading">Where it gets harder</h4>



<ul class="wp-block-list">
<li><strong>Parallel tests.</strong> Registrations live in one shared container, so tests that run at the same time can overwrite each other&#8217;s mocks. To keep them separate, each test gets its own container through a <code>@TaskLocal</code>. The drawback is making that work reliably: task-local values only reach code that runs inside the test&#8217;s task. Point-Free put a lot of work into this in their swift-dependencies library, and I&#8217;m still not sure I&#8217;d catch every case. I&#8217;d rather not spend my time hunting test failures that only show up sometimes.</li>



<li><strong>Hidden dependencies.</strong> Dependencies no longer show up in the initializer. Nothing reminds you to register a mock, so it&#8217;s easy to forget one, for example in a preview, and silently call the live service.</li>



<li><strong>Multi-window apps.</strong> Factory&#8217;s scopes are app-wide, not per window. A repository, an object that holds state below the UI like an image cache, is shared by every window if it&#8217;s a singleton. On iPad and Mac, each window often needs its own repository, with its own cache or selection, while the token store stays one per app. With the environment, this comes for free: each window has its own view tree, so a repository created inside the <code>WindowGroup</code> content exists once per window. With Factory, you need a custom scope or have to pass a window identifier around. More on per-window lifetimes in Building the Dependency Graph in SwiftUI.</li>
</ul>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h4 class="wp-block-heading">My take</h4>



<p class="wp-block-paragraph">I show DI frameworks as an option, not a recommendation. They look easy at the start: register a dependency, add <code>@Injected</code>, done. The problems come later. If the scopes and overrides aren&#8217;t set up right, you get shared state you didn&#8217;t expect, like the multi-window case above, and the dependencies no longer show up in the initializer. And once the whole app resolves its dependencies through the framework, moving away from it means touching every view model.</p>



<p class="wp-block-paragraph">The initializer and environment approach needs more code, but it&#8217;s plain Swift and SwiftUI that you can read, understand, and change.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Outlook: MVVM-C</h2>



<p class="wp-block-paragraph">There&#8217;s one more way to look at this. With coordinators, views no longer create their view models at all. The coordinator builds each view model with plain initializer injection and passes the dependencies from parent to child coordinator. That replaces most of the environment setup from this post, and gives per-window instances with one coordinator per window.</p>



<p class="wp-block-paragraph">That&#8217;s a bigger topic, so it gets two posts of its own: MVVM-C in SwiftUI: Why, What, and How, and Dependency Injection With MVVM-C.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Summary</h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">Approach</th><th class="has-text-align-left" data-align="left">Verdict</th></tr></thead><tbody><tr><td class="has-text-align-left" data-align="left">Service through the view&#8217;s <code>init</code></td><td class="has-text-align-left" data-align="left">Works for a single screen, breaks down once the screen is used inside other views</td></tr><tr><td class="has-text-align-left" data-align="left">Service in the environment</td><td class="has-text-align-left" data-align="left">What I use: reaches screens at any depth, and one override switches previews and UI tests to mocks</td></tr><tr><td class="has-text-align-left" data-align="left">DI container like Factory</td><td class="has-text-align-left" data-align="left">An option, with trade-offs: parallel tests, hidden dependencies, and multi-window apps</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">There&#8217;s also a limit. Everything in this post works because the services are stateless, so a live default and extra copies are harmless. A token store or a repository with a cache holds state, and there a live default would quietly create a second instance. Where and how to create those is the topic of Building the Dependency Graph in SwiftUI.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>


<div class="gb-container gb-container-c5dedc2e">
<div class="gb-container gb-container-f7a433c7">
<div class="gb-container gb-container-7a8dc7a3">

<figure class="gb-block-image gb-block-image-f04fbbad"><a href="https://www.swiftyplace.com/free-swiftui-layout-cookbook" target="_blank" rel="noopener noreferrer"><img decoding="async" width="1446" height="1552" class="gb-image gb-image-f04fbbad" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm.webp" alt="" title="lead magnet mvvm" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm.webp 1446w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-280x300.webp 280w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-954x1024.webp 954w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-768x824.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-1431x1536.webp 1431w" sizes="(max-width: 1446px) 100vw, 1446px" /></a></figure>

</div>

<div class="gb-container gb-container-98352fe6">

<h4 class="gb-headline gb-headline-4aacd94c gb-headline-text">Get the MVVM SwiftUI Cheat Sheet</h4>



<p class="gb-headline gb-headline-5e6c4f85 gb-headline-text">The cheat sheet puts the whole system on a few pages: what goes in a view model, which view owns it, how to pass it down the tree, common mistakes, and code skeletons you can copy.</p>


<div class="gb-container gb-container-34a8ad02">

<a class="gb-button gb-button-63e90e76 gb-button-blue" href="https://school.swiftyplace.com/f/swiftui-mvvm-cheat-sheet" target="_blank" rel="noopener noreferrer"><span class="gb-button-text">Get the free cheat sheet</span><span class="gb-icon"><svg aria-hidden="true" role="img" height="1em" width="1em" viewBox="0 0 256 512" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M224.3 273l-136 136c-9.4 9.4-24.6 9.4-33.9 0l-22.6-22.6c-9.4-9.4-9.4-24.6 0-33.9l96.4-96.4-96.4-96.4c-9.4-9.4-9.4-24.6 0-33.9L54.3 103c9.4-9.4 24.6-9.4 33.9 0l136 136c9.5 9.4 9.5 24.6.1 34z"></path></svg></span></a>

</div>
</div>
</div>
</div>


<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h4 class="wp-block-heading">Further Reading</h4>



<ul class="wp-block-list">
<li><a href="https://www.swiftyplace.com/blog/swiftui-mvvm" data-type="link" data-id="https://www.swiftyplace.com/blog/swiftui-mvvm">What Is a View Model in SwiftUI, Really?</a></li>



<li><a href="https://www.swiftyplace.com/blog/mvvm-view-model-use-case">When to Use a View Model in SwiftUI (and When It’s Overkill)</a></li>



<li><a href="https://www.swiftyplace.com/blog/mvvm-what-in-viewmodel">What Should Go in a View Model in SwiftUI?</a></li>



<li><a href="https://www.swiftyplace.com/blog/dependency-injection-swift" data-type="link" data-id="https://www.swiftyplace.com/blog/dependency-injection-swift">Dependency Injection in Swift: Services, Protocols, and Testable View Models</a></li>
</ul>



<p class="wp-block-paragraph"></p>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/dependency-injection-swiftui">Dependency Injection in SwiftUI: Initializer, Environment, or Container</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.swiftyplace.com/blog/dependency-injection-swiftui/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Dependency Injection in Swift: Services, Protocols, and Testable View Models</title>
		<link>https://www.swiftyplace.com/blog/dependency-injection-swift?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=dependency-injection-swift</link>
					<comments>https://www.swiftyplace.com/blog/dependency-injection-swift#respond</comments>
		
		<dc:creator><![CDATA[Karin Prater]]></dc:creator>
		<pubDate>Sun, 01 Nov 2026 12:10:16 +0000</pubDate>
				<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Architecture]]></category>
		<guid isPermaLink="false">https://www.swiftyplace.com/?p=1005784</guid>

					<description><![CDATA[<p>Your view model needs UserDefaults, the network, or the file system, and that’s exactly what breaks your previews and tests. Learn dependency injection in Swift step by step: move that work into services, let view models depend on a protocol, and swap in mocks for SwiftUI previews and unit tests that are fast and reliable.</p>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/dependency-injection-swift">Dependency Injection in Swift: Services, Protocols, and Testable View Models</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph"><a href="https://www.swiftyplace.com/blog/mvvm-what-in-viewmodel">In What Should Go in a View Model?</a>, we defined the view model&#8217;s job: it owns UI state and is responsible for mutating that state properly and consistently. But to do that job, it almost always needs something from outside your own code. Products come from the network. Themes are saved to disk. Settings live in <code>UserDefaults</code>.</p>



<p class="wp-block-paragraph">The easiest way to get there is to write that code right into the view model. A <code>URLSession</code> call here, a <code>JSONDecoder</code> there. It works, until you open a preview and it spins forever, or crashes because there&#8217;s no server. Or until you try to write a test, and it&#8217;s slow, fails randomly, or can&#8217;t be written at all.</p>



<p class="wp-block-paragraph">In this post, I&#8217;ll show you how to fix both problems with dependency injection in Swift: move that work into services, let your view models depend on a protocol instead of the real thing, and inject what you need. By the end, every view model can run in a preview and a unit test without touching <code>UserDefaults</code> or the network.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Why keeping UserDefaults Code Inside the View Model becomes a Problem</h2>



<p class="wp-block-paragraph">Let&#8217;s start with a simple example. Users can mark products as favorites, and the favorites are saved in <code>UserDefaults</code>. Here&#8217;s the version most of us write first, with <code>UserDefaults</code> right inside the view model:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@MainActor
@Observable
final class FavoritesViewModel {
    private(set) var favoriteIDs: Set&lt;Product.ID> = []
    private let key = "favoriteProductIDs"

    init() {
        // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a0.png" alt="⚠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Reading UserDefaults inside the view model
        favoriteIDs = Set(UserDefaults.standard.stringArray(forKey: key) ?? [])
    }

    func toggleFavorite(_ product: Product) {
        if favoriteIDs.contains(product.id) {
            favoriteIDs.remove(product.id)
        } else {
            favoriteIDs.insert(product.id)
        }
        // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a0.png" alt="⚠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Writing UserDefaults inside the view model
        UserDefaults.standard.set(Array(favoriteIDs), forKey: key)
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">FavoritesViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> favoriteIDs: </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">&lt;Product.ID&gt; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> key </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">favoriteProductIDs</span><span style="color: #DEE492">&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">() {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #7B7F8B">// &#x26a0; Reading UserDefaults inside the view model</span></span>
<span class="line"><span style="color: #F6F6F4">        favoriteIDs </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">(UserDefaults.standard.</span><span style="color: #97E1F1">stringArray</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">forKey</span><span style="color: #F6F6F4">: key) </span><span style="color: #F286C4">??</span><span style="color: #F6F6F4"> [])</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">toggleFavorite</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">product</span><span style="color: #F6F6F4">: Product) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> favoriteIDs.</span><span style="color: #97E1F1">contains</span><span style="color: #F6F6F4">(product.id) {</span></span>
<span class="line"><span style="color: #F6F6F4">            favoriteIDs.</span><span style="color: #97E1F1">remove</span><span style="color: #F6F6F4">(product.id)</span></span>
<span class="line"><span style="color: #F6F6F4">        } </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            favoriteIDs.</span><span style="color: #97E1F1">insert</span><span style="color: #F6F6F4">(product.id)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #7B7F8B">// &#x26a0; Writing UserDefaults inside the view model</span></span>
<span class="line"><span style="color: #F6F6F4">        UserDefaults.standard.</span><span style="color: #BF9EEE">set</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1; font-style: italic">Array</span><span style="color: #F6F6F4">(favoriteIDs), </span><span style="color: #97E1F1">forKey</span><span style="color: #F6F6F4">: key)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">This works in the app. The problems show up everywhere else.</p>



<p class="wp-block-paragraph"><strong>Previews keep what you tapped.</strong> Tap a heart in the preview, and it&#8217;s written to the real <code>UserDefaults</code>. Open the preview again tomorrow, and the favorite is still there. You can&#8217;t reliably show the empty state, and to show a screen with three favorites, you have to tap them again every time, or write test data into <code>UserDefaults</code> by hand.</p>



<p class="wp-block-paragraph"><strong>Tests depend on each other.</strong> Say one test checks that toggling adds a favorite, and another checks that a new view model starts with no favorites:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@Test func toggleAddsFavorite() {
    let viewModel = FavoritesViewModel()
    viewModel.toggleFavorite(Product.samples&#91;0&#93;)
    #expect(viewModel.favoriteIDs.count == 1)
}

@Test func startsWithNoFavorites() {
    let viewModel = FavoritesViewModel()
    #expect(viewModel.favoriteIDs.isEmpty) // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> fails if the other test ran first
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@Test</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">toggleAddsFavorite</span><span style="color: #F6F6F4">() {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">FavoritesViewModel</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    viewModel.</span><span style="color: #97E1F1">toggleFavorite</span><span style="color: #F6F6F4">(Product.samples&#91;</span><span style="color: #BF9EEE">0</span><span style="color: #F6F6F4">&#93;)</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">#expect</span><span style="color: #F6F6F4">(viewModel.favoriteIDs.</span><span style="color: #BF9EEE">count</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">1</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">@Test</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">startsWithNoFavorites</span><span style="color: #F6F6F4">() {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">FavoritesViewModel</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">#expect</span><span style="color: #F6F6F4">(viewModel.favoriteIDs.</span><span style="color: #BF9EEE">isEmpty</span><span style="color: #F6F6F4">) </span><span style="color: #7B7F8B">// &#x274c; fails if the other test ran first</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Both tests read and write the same key in the same <code>UserDefaults</code>. Whether the second one passes depends on which test runs first, and on what earlier runs left behind. Run them in parallel, and they fail at random. That&#8217;s the worst kind of test: one you stop trusting.</p>



<p class="wp-block-paragraph"><strong>The view model has two jobs.</strong> It manages the favorites as UI state, and it knows how they&#8217;re stored: the key, the format, the storage API. Switch to iCloud or a file later, and you rewrite the view model. Need favorites in a second view model, and you copy the storage code.</p>



<p class="wp-block-paragraph"><code>UserDefaults</code> is just one example. The problem has a name: a <strong>shared external dependency</strong>, a resource outside your own code that&#8217;s shared with the system, the rest of your app, and other tests. Think of:</p>



<ul class="wp-block-list">
<li>the network</li>



<li>the file system</li>



<li><code>UserDefaults</code> and the Keychain</li>



<li>HealthKit, location, contacts</li>



<li>even the current date and time</li>
</ul>



<p class="wp-block-paragraph">With the network, it gets worse: requests are slow, and they fail for reasons that have nothing to do with your code. That leads to a simple rule: <strong>shared external dependencies go behind a boundary you control.</strong> Everything else, like your models and the view model&#8217;s own logic, can run for real.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Step 1: Move the Storage Code Into a Service</h2>



<p class="wp-block-paragraph">So the storage code moves into a <strong>service</strong>. A service is a helper worker: a stateless type that handles one kind of work with a shared external dependency.</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>nonisolated struct FavoritesService {
    private let key = "favoriteProductIDs"

    func loadFavoriteIDs() -> Set&lt;Product.ID> {
        Set(UserDefaults.standard.stringArray(forKey: key) ?? [])
    }

    func saveFavoriteIDs(_ ids: Set&lt;Product.ID>) {
        UserDefaults.standard.set(Array(ids), forKey: key)
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">nonisolated</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">FavoritesService</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> key </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">favoriteProductIDs</span><span style="color: #DEE492">&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">loadFavoriteIDs</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">&lt;Product.ID&gt; {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">(UserDefaults.standard.</span><span style="color: #97E1F1">stringArray</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">forKey</span><span style="color: #F6F6F4">: key) </span><span style="color: #F286C4">??</span><span style="color: #F6F6F4"> [])</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">saveFavoriteIDs</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">ids</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">&lt;Product.ID&gt;) {</span></span>
<span class="line"><span style="color: #F6F6F4">        UserDefaults.standard.</span><span style="color: #BF9EEE">set</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1; font-style: italic">Array</span><span style="color: #F6F6F4">(ids), </span><span style="color: #97E1F1">forKey</span><span style="color: #F6F6F4">: key)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<ul class="wp-block-list">
<li><strong>Stateless:</strong> it has no properties that change. It takes input, does the work, and returns a result. The favorites themselves stay in the view model.</li>



<li><strong>Reusable:</strong> any view model that needs favorites can use it, like a product list and a product detail screen.</li>



<li><strong>Ready for the background:</strong> it&#8217;s <code>nonisolated</code>, so it isn&#8217;t tied to the main actor. Reading <code>UserDefaults</code> is fast, but for slow work like network requests, the service can run its functions in the background, as you&#8217;ll see in the second example.</li>
</ul>



<p class="wp-block-paragraph">The view model keeps its job, managing the state, and hands the storage work to the service:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@Observable
final class FavoritesViewModel {
    private(set) var favoriteIDs: Set&lt;Product.ID> = []
    private let favoritesService = FavoritesService()

    init() {
        favoriteIDs = favoritesService.loadFavoriteIDs()
    }

    func toggleFavorite(_ product: Product) {
        if favoriteIDs.contains(product.id) {
            favoriteIDs.remove(product.id)
        } else {
            favoriteIDs.insert(product.id)
        }
        favoritesService.saveFavoriteIDs(favoriteIDs)
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">FavoritesViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> favoriteIDs: </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">&lt;Product.ID&gt; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> favoritesService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">FavoritesService</span><span style="color: #F6F6F4">()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">() {</span></span>
<span class="line"><span style="color: #F6F6F4">        favoriteIDs </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> favoritesService.</span><span style="color: #97E1F1">loadFavoriteIDs</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">toggleFavorite</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">product</span><span style="color: #F6F6F4">: Product) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> favoriteIDs.</span><span style="color: #97E1F1">contains</span><span style="color: #F6F6F4">(product.id) {</span></span>
<span class="line"><span style="color: #F6F6F4">            favoriteIDs.</span><span style="color: #97E1F1">remove</span><span style="color: #F6F6F4">(product.id)</span></span>
<span class="line"><span style="color: #F6F6F4">        } </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            favoriteIDs.</span><span style="color: #97E1F1">insert</span><span style="color: #F6F6F4">(product.id)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">        favoritesService.</span><span style="color: #97E1F1">saveFavoriteIDs</span><span style="color: #F6F6F4">(favoriteIDs)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">One naming rule I stick to: a service never holds UI state. If something called a &#8220;service&#8221; has <code>@Observable</code> properties that views read, it&#8217;s a view model with the wrong name.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Step 2: Dependency Injection With a Protocol (the Dependency Inversion Principle)</h2>



<p class="wp-block-paragraph">Moving the storage code into a service cleaned up the view model. But it didn&#8217;t solve the preview and test problem yet. The view model creates the service itself, so it&#8217;s still locked to the real <code>UserDefaults</code>:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@Observable
final class FavoritesViewModel {
    private(set) var favoriteIDs: Set&lt;Product.ID> = []
    private let favoritesService = FavoritesService() // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a0.png" alt="⚠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> always the real UserDefaults

    // ...
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">FavoritesViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> favoriteIDs: </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">&lt;Product.ID&gt; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> favoritesService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">FavoritesService</span><span style="color: #F6F6F4">() </span><span style="color: #7B7F8B">// &#x26a0; always the real UserDefaults</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// ...</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">No preview or test can change that. The fix is to flip the dependency around. Instead of depending on the concrete service, the view model depends on a description of what it needs: a <strong>protocol</strong>. That&#8217;s the <strong>Dependency Inversion Principle (DIP)</strong>: high-level code, like your view model, shouldn&#8217;t depend on low-level details, like the code that reads and writes UserDefaults. Both depend on an abstraction in between: the protocol.</p>


<div class="gb-container gb-container-1f50d190">

<figure class="gb-block-image gb-block-image-80d3092d"><img decoding="async" width="970" height="516" class="gb-image gb-image-80d3092d" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swift-1.webp" alt="dependency injection swift with a viewmodel to test logic" title="dependency-injection-swift-1" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swift-1.webp 970w, https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swift-1-300x160.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swift-1-768x409.webp 768w" sizes="(max-width: 970px) 100vw, 970px" /></figure>

</div>


<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The protocol describes what the view model needs:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>nonisolated protocol FavoritesService: Sendable {
    func loadFavoriteIDs() -> Set&lt;Product.ID>
    func saveFavoriteIDs(_ ids: Set&lt;Product.ID>)
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">nonisolated</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">protocol</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">FavoritesService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Sendable </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">loadFavoriteIDs</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">&lt;Product.ID&gt;</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">saveFavoriteIDs</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">ids</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">&lt;Product.ID&gt;)</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The service we wrote above becomes the live implementation:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>nonisolated struct LiveFavoritesService: FavoritesService {
    private let key = "favoriteProductIDs"

    func loadFavoriteIDs() -> Set&lt;Product.ID> {
        Set(UserDefaults.standard.stringArray(forKey: key) ?? [])
    }

    func saveFavoriteIDs(_ ids: Set&lt;Product.ID>) {
        UserDefaults.standard.set(Array(ids), forKey: key)
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">nonisolated</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">LiveFavoritesService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">FavoritesService </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> key </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">favoriteProductIDs</span><span style="color: #DEE492">&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">loadFavoriteIDs</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">&lt;Product.ID&gt; {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">(UserDefaults.standard.</span><span style="color: #97E1F1">stringArray</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">forKey</span><span style="color: #F6F6F4">: key) </span><span style="color: #F286C4">??</span><span style="color: #F6F6F4"> [])</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">saveFavoriteIDs</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">ids</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">&lt;Product.ID&gt;) {</span></span>
<span class="line"><span style="color: #F6F6F4">        UserDefaults.standard.</span><span style="color: #BF9EEE">set</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1; font-style: italic">Array</span><span style="color: #F6F6F4">(ids), </span><span style="color: #97E1F1">forKey</span><span style="color: #F6F6F4">: key)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The protocol is <code>nonisolated</code> and <code>Sendable</code>, so the view model on the main actor can hold it, and implementations aren&#8217;t tied to the main actor.</p>



<p class="wp-block-paragraph">Now the view model receives whichever implementation you want through its initializer, with the live service as the default:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@MainActor
@Observable
final class FavoritesViewModel {
    private(set) var favoriteIDs: Set&lt;Product.ID> = []
    private let favoritesService: FavoritesService

    init(favoritesService: FavoritesService = LiveFavoritesService()) {
        self.favoritesService = favoritesService
        favoriteIDs = favoritesService.loadFavoriteIDs()
    }

    func toggleFavorite(_ product: Product) {
        if favoriteIDs.contains(product.id) {
            favoriteIDs.remove(product.id)
        } else {
            favoriteIDs.insert(product.id)
        }
        favoritesService.saveFavoriteIDs(favoriteIDs)
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">FavoritesViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> favoriteIDs: </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">&lt;Product.ID&gt; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> favoritesService: FavoritesService</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">favoritesService</span><span style="color: #F6F6F4">: FavoritesService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">LiveFavoritesService</span><span style="color: #F6F6F4">()) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.favoritesService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> favoritesService</span></span>
<span class="line"><span style="color: #F6F6F4">        favoriteIDs </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> favoritesService.</span><span style="color: #97E1F1">loadFavoriteIDs</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">toggleFavorite</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">product</span><span style="color: #F6F6F4">: Product) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> favoriteIDs.</span><span style="color: #97E1F1">contains</span><span style="color: #F6F6F4">(product.id) {</span></span>
<span class="line"><span style="color: #F6F6F4">            favoriteIDs.</span><span style="color: #97E1F1">remove</span><span style="color: #F6F6F4">(product.id)</span></span>
<span class="line"><span style="color: #F6F6F4">        } </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            favoriteIDs.</span><span style="color: #97E1F1">insert</span><span style="color: #F6F6F4">(product.id)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">        favoritesService.</span><span style="color: #97E1F1">saveFavoriteIDs</span><span style="color: #F6F6F4">(favoriteIDs)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">In the app, nothing changes: <code>FavoritesViewModel()</code> uses the live service. Previews and tests pass in a mock. That&#8217;s all dependency injection is: the view model gets its dependencies from outside instead of creating them itself.</p>



<p class="wp-block-paragraph">Initializer injection is the simplest way, and it&#8217;s what this post uses. It&#8217;s not the only one. In a real SwiftUI app, the bigger question is how dependencies get from the app&#8217;s entry point to every view model that needs them, especially when several view models share one instance. Common approaches are the SwiftUI environment and a dependency container. That&#8217;s a topic of its own, which I cover in SwiftUI Dependency Injection: Initializer, Environment, or Container?.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">What You Gain: Previews for Every State</h2>



<p class="wp-block-paragraph">Here&#8217;s where the protocol pays off first. A mock conforms to the same protocol, but instead of touching <code>UserDefaults</code>, it starts with whatever favorites you give it and keeps everything in memory:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>nonisolated struct MockFavoritesService: FavoritesService {
    var favoriteIDs: Set&lt;Product.ID> = []

    func loadFavoriteIDs() -> Set&lt;Product.ID> { favoriteIDs }
    func saveFavoriteIDs(_ ids: Set&lt;Product.ID>) {}
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">nonisolated</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">MockFavoritesService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">FavoritesService </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> favoriteIDs: </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">&lt;Product.ID&gt; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">loadFavoriteIDs</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">&lt;Product.ID&gt; { favoriteIDs }</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">saveFavoriteIDs</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">ids</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">&lt;Product.ID&gt;) {}</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Now each preview injects a differently configured mock. <code>@Previewable @State</code> makes the preview the owner of the view model, just like the parent view in your app, so it&#8217;s created once instead of on every preview update:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>#Preview("No Favorites") {
    @Previewable @State var viewModel = FavoritesViewModel(
        favoritesService: MockFavoritesService()
    )
    FavoritesView(viewModel: viewModel)
}

#Preview("With Favorites") {
    @Previewable @State var viewModel = FavoritesViewModel(
        favoritesService: MockFavoritesService(
            favoriteIDs: Set(Product.samples.prefix(3).map(.id))
        )
    )
    FavoritesView(viewModel: viewModel)
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">No Favorites</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Previewable</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">FavoritesViewModel</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">favoritesService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">MockFavoritesService</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    )</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">FavoritesView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">viewModel</span><span style="color: #F6F6F4">: viewModel)</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">With Favorites</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Previewable</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">FavoritesViewModel</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">favoritesService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">MockFavoritesService</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">favoriteIDs</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Set</span><span style="color: #F6F6F4">(Product.samples.</span><span style="color: #97E1F1">prefix</span><span style="color: #F6F6F4">(</span><span style="color: #BF9EEE">3</span><span style="color: #F6F6F4">).</span><span style="color: #97E1F1">map</span><span style="color: #F6F6F4">(.id))</span></span>
<span class="line"><span style="color: #F6F6F4">        )</span></span>
<span class="line"><span style="color: #F6F6F4">    )</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">FavoritesView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">viewModel</span><span style="color: #F6F6F4">: viewModel)</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Every state of the screen is one click away in Xcode, and tapping favorites in the preview never changes what&#8217;s saved on your Mac or simulator. Keep sample data like <code>Product.samples</code> next to the model, so previews and tests share it.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">What You Gain: Reliable Unit Tests for View Models</h2>



<p class="wp-block-paragraph">The same mock makes unit tests straightforward. Inject it, call a method, and check the state:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>import Testing

@MainActor
struct FavoritesViewModelTests {
    @Test func toggleAddsFavorite() {
        let product = Product.samples&#91;0&#93;
        let viewModel = FavoritesViewModel(favoritesService: MockFavoritesService())

        viewModel.toggleFavorite(product)

        #expect(viewModel.favoriteIDs == &#91;product.id&#93;)
    }

    @Test func toggleRemovesExistingFavorite() {
        let product = Product.samples&#91;0&#93;
        let viewModel = FavoritesViewModel(
            favoritesService: MockFavoritesService(favoriteIDs: &#91;product.id&#93;)
        )

        viewModel.toggleFavorite(product)

        #expect(viewModel.favoriteIDs.isEmpty)
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">import</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Testing</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">FavoritesViewModelTests</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Test</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">toggleAddsFavorite</span><span style="color: #F6F6F4">() {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> product </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> Product.samples&#91;</span><span style="color: #BF9EEE">0</span><span style="color: #F6F6F4">&#93;</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">FavoritesViewModel</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">favoritesService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">MockFavoritesService</span><span style="color: #F6F6F4">())</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">        viewModel.</span><span style="color: #97E1F1">toggleFavorite</span><span style="color: #F6F6F4">(product)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">#expect</span><span style="color: #F6F6F4">(viewModel.favoriteIDs </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> &#91;product.id&#93;)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Test</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">toggleRemovesExistingFavorite</span><span style="color: #F6F6F4">() {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> product </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> Product.samples&#91;</span><span style="color: #BF9EEE">0</span><span style="color: #F6F6F4">&#93;</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">FavoritesViewModel</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">favoritesService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">MockFavoritesService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">favoriteIDs</span><span style="color: #F6F6F4">: &#91;product.id&#93;)</span></span>
<span class="line"><span style="color: #F6F6F4">        )</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">        viewModel.</span><span style="color: #97E1F1">toggleFavorite</span><span style="color: #F6F6F4">(product)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">#expect</span><span style="color: #F6F6F4">(viewModel.favoriteIDs.</span><span style="color: #BF9EEE">isEmpty</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:18px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">This solves the leaky test problem from the beginning. With the live service, the first test would write a favorite to the real <code>UserDefaults</code>, and the second test, or the next run, would find it there. With the mock, every test starts with exactly the favorites it sets up, and nothing is left behind. That also means the tests are fast and can run in parallel.</p>



<p class="wp-block-paragraph">Test what the view model is responsible for: how its state changes when you call its methods. What you don&#8217;t test here is <code>UserDefaults</code> itself, and you don&#8217;t test the UI; the view model only exposes state.</p>



<div style="height:18px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">A Second Example: Loading Products From the Network</h2>



<p class="wp-block-paragraph">The same pattern works for every shared external dependency. The network adds two things the favorites example didn&#8217;t need: the work is slow, so it should run in the background, and the screen now has loading and error states.</p>



<p class="wp-block-paragraph">The protocol describes what the view model needs, and the live service does the request and decoding in the background with <code>@concurrent</code>:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>nonisolated protocol ProductService: Sendable {
    func fetchProducts() async throws -> &#91;Product&#93;
}

nonisolated struct LiveProductService: ProductService {
    @concurrent
    func fetchProducts() async throws -> &#91;Product&#93; {
        let url = URL(string: "https://api.example.com/products")!
        let (data, _) = try await URLSession.shared.data(from: url)
        return try JSONDecoder().decode(&#91;Product&#93;.self, from: data)
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">nonisolated</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">protocol</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ProductService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Sendable </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">fetchProducts</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">throws</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> &#91;Product&#93;</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">nonisolated</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">LiveProductService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">ProductService </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@concurrent</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">fetchProducts</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">throws</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> &#91;Product&#93; {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> url </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">URL</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">string</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">https://api.example.com/products</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span><span style="color: #F286C4">!</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> (data, </span><span style="color: #BF9EEE">_</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> URLSession.shared.</span><span style="color: #97E1F1">data</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">from</span><span style="color: #F6F6F4">: url)</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">JSONDecoder</span><span style="color: #F6F6F4">().</span><span style="color: #97E1F1">decode</span><span style="color: #F6F6F4">(&#91;Product&#93;.</span><span style="color: #F286C4">self</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">from</span><span style="color: #F6F6F4">: data)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:18px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The view model receives the service through its initializer and manages the loading state:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@MainActor
@Observable
final class ProductViewModel {
    private(set) var state: LoadingState&lt;&#91;Product&#93;> = .idle
    private let productService: ProductService

    init(productService: ProductService = LiveProductService()) {
        self.productService = productService
    }

    func load() async {
        state = .loading
        do {
            state = .loaded(try await productService.fetchProducts())
        } catch {
            state = .failed("Couldn't load products.")
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> state: LoadingState&lt;&#91;Product&#93;&gt; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .idle</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> productService: ProductService</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">productService</span><span style="color: #F6F6F4">: ProductService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">LiveProductService</span><span style="color: #F6F6F4">()) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.productService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> productService</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">load</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        state </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .loading</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">do</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            state </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .</span><span style="color: #97E1F1">loaded</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> productService.</span><span style="color: #97E1F1">fetchProducts</span><span style="color: #F6F6F4">())</span></span>
<span class="line"><span style="color: #F6F6F4">        } </span><span style="color: #F286C4">catch</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            state </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .</span><span style="color: #97E1F1">failed</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Couldn&#39;t load products.</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:18px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The mock can now do three things: return products, throw an error, or wait to show the loading state:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>nonisolated struct MockProductService: ProductService {
    var products: &#91;Product&#93; = []
    var error: Error? = nil
    var delay: Duration = .zero

    func fetchProducts() async throws -> &#91;Product&#93; {
        try await Task.sleep(for: delay)
        if let error { throw error }
        return products
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">nonisolated</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">MockProductService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">ProductService </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> products: &#91;Product&#93; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> error: </span><span style="color: #97E1F1; font-style: italic">Error</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">nil</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> delay: Duration </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .zero</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">fetchProducts</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">throws</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> &#91;Product&#93; {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> Task.</span><span style="color: #97E1F1">sleep</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">for</span><span style="color: #F6F6F4">: delay)</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> error { </span><span style="color: #F286C4">throw</span><span style="color: #F6F6F4"> error }</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> products</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:18px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">That gives you a preview for every state of the screen, including the empty and error states that are usually hard to reproduce:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>#Preview("Loaded") {
    @Previewable @State var viewModel = ProductViewModel(
        productService: MockProductService(products: Product.samples)
    )
    ProductListView(viewModel: viewModel)
}

#Preview("Empty") {
    @Previewable @State var viewModel = ProductViewModel(
        productService: MockProductService(products: [])
    )
    ProductListView(viewModel: viewModel)
}

#Preview("Error") {
    @Previewable @State var viewModel = ProductViewModel(
        productService: MockProductService(error: URLError(.notConnectedToInternet))
    )
    ProductListView(viewModel: viewModel)
}

#Preview("Loading") {
    @Previewable @State var viewModel = ProductViewModel(
        productService: MockProductService(delay: .seconds(3600))
    )
    ProductListView(viewModel: viewModel)
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Loaded</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Previewable</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">productService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">MockProductService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">products</span><span style="color: #F6F6F4">: Product.samples)</span></span>
<span class="line"><span style="color: #F6F6F4">    )</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">ProductListView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">viewModel</span><span style="color: #F6F6F4">: viewModel)</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Empty</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Previewable</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">productService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">MockProductService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">products</span><span style="color: #F6F6F4">: [])</span></span>
<span class="line"><span style="color: #F6F6F4">    )</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">ProductListView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">viewModel</span><span style="color: #F6F6F4">: viewModel)</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Error</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Previewable</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">productService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">MockProductService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">error</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">URLError</span><span style="color: #F6F6F4">(.notConnectedToInternet))</span></span>
<span class="line"><span style="color: #F6F6F4">    )</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">ProductListView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">viewModel</span><span style="color: #F6F6F4">: viewModel)</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #97E1F1">#Preview</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Loading</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Previewable</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">productService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">MockProductService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">delay</span><span style="color: #F6F6F4">: .</span><span style="color: #97E1F1">seconds</span><span style="color: #F6F6F4">(</span><span style="color: #BF9EEE">3600</span><span style="color: #F6F6F4">))</span></span>
<span class="line"><span style="color: #F6F6F4">    )</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">ProductListView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">viewModel</span><span style="color: #F6F6F4">: viewModel)</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:18px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">And the tests check how the state changes for success and failure:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@MainActor
struct ProductViewModelTests {
    @Test func loadStoresProducts() async {
        let viewModel = ProductViewModel(
            productService: MockProductService(products: Product.samples)
        )
        await viewModel.load()
        #expect(viewModel.state == .loaded(Product.samples))
    }

    @Test func loadFailureSetsErrorState() async {
        let viewModel = ProductViewModel(
            productService: MockProductService(error: URLError(.timedOut))
        )
        await viewModel.load()
        #expect(viewModel.state == .failed("Couldn't load products."))
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ProductViewModelTests</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Test</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">loadStoresProducts</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">productService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">MockProductService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">products</span><span style="color: #F6F6F4">: Product.samples)</span></span>
<span class="line"><span style="color: #F6F6F4">        )</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> viewModel.</span><span style="color: #97E1F1">load</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">#expect</span><span style="color: #F6F6F4">(viewModel.state </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> .</span><span style="color: #97E1F1">loaded</span><span style="color: #F6F6F4">(Product.samples))</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Test</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">loadFailureSetsErrorState</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">productService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">MockProductService</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">error</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">URLError</span><span style="color: #F6F6F4">(.timedOut))</span></span>
<span class="line"><span style="color: #F6F6F4">        )</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> viewModel.</span><span style="color: #97E1F1">load</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">#expect</span><span style="color: #F6F6F4">(viewModel.state </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> .</span><span style="color: #97E1F1">failed</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Couldn&#39;t load products.</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">))</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:18px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">For <code>#expect</code> to compare states, <code>LoadingState</code> and <code>Product</code> need to be <code>Equatable</code>. No server, no network, no waiting: these tests give the same result every time.</p>



<div style="height:18px" aria-hidden="true" class="wp-block-spacer"></div>



<h4 class="wp-block-heading">Building Up: Sharing Networking Logic With an API Client</h4>



<p class="wp-block-paragraph">As your app grows, you&#8217;ll have more services: products, cart, orders. Each one builds a URL, sends a request, and decodes the JSON. The same few lines, repeated in every service. This is where services really pay off: logic that several of them need can move into one shared place.</p>



<p class="wp-block-paragraph">For networking, that&#8217;s usually a small <code>APIClient</code>:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>nonisolated struct APIClient {
    var baseURL = URL(string: "https://api.example.com")!

    @concurrent
    func get&lt;T: Decodable>(_ path: String) async throws -> T {
        let url = baseURL.appending(path: path)
        let (data, _) = try await URLSession.shared.data(from: url)
        return try JSONDecoder().decode(T.self, from: data)
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">nonisolated</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">APIClient</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> baseURL </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">URL</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">string</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">https://api.example.com</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span><span style="color: #F286C4">!</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@concurrent</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">get</span><span style="color: #F6F6F4">&lt;</span><span style="color: #BF9EEE; font-style: italic">T</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Decodable</span><span style="color: #F6F6F4">&gt;(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">path</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">throws</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> T {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> url </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> baseURL.</span><span style="color: #97E1F1">appending</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">path</span><span style="color: #F6F6F4">: path)</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> (data, </span><span style="color: #BF9EEE">_</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> URLSession.shared.</span><span style="color: #97E1F1">data</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">from</span><span style="color: #F6F6F4">: url)</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">JSONDecoder</span><span style="color: #F6F6F4">().</span><span style="color: #97E1F1">decode</span><span style="color: #F6F6F4">(T.</span><span style="color: #F286C4">self</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">from</span><span style="color: #F6F6F4">: data)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Every live service uses it, and only describes <em>what</em> it fetches:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>nonisolated struct LiveProductService: ProductService {
    private let apiClient: APIClient

    init(apiClient: APIClient = APIClient()) {
        self.apiClient = apiClient
    }

    func fetchProducts() async throws -> &#91;Product&#93; {
        try await apiClient.get("products")
    }
}

nonisolated struct LiveCartService: CartService {
    private let apiClient: APIClient

    init(apiClient: APIClient = APIClient()) {
        self.apiClient = apiClient
    }

    func fetchCart() async throws -> Cart {
        try await apiClient.get("cart")
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">nonisolated</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">LiveProductService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">ProductService </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> apiClient: APIClient</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">apiClient</span><span style="color: #F6F6F4">: APIClient </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">APIClient</span><span style="color: #F6F6F4">()) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.apiClient </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> apiClient</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">fetchProducts</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">throws</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> &#91;Product&#93; {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> apiClient.</span><span style="color: #97E1F1">get</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">products</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">nonisolated</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">LiveCartService</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">CartService </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> apiClient: APIClient</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">apiClient</span><span style="color: #F6F6F4">: APIClient </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">APIClient</span><span style="color: #F6F6F4">()) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.apiClient </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> apiClient</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">fetchCart</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">throws</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> Cart {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> apiClient.</span><span style="color: #97E1F1">get</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">cart</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>


<div class="gb-container gb-container-ac9ee019">

<figure class="gb-block-image gb-block-image-eb3f8b3f"><img loading="lazy" decoding="async" width="961" height="655" class="gb-image gb-image-eb3f8b3f" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swift-2.webp" alt="dependency injection in swift for networking, reusable networking layer" title="dependency-injection-swift-2" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swift-2.webp 961w, https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swift-2-300x204.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swift-2-768x523.webp 768w" sizes="auto, (max-width: 961px) 100vw, 961px" /></figure>

</div>


<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The <em>how</em> now lives in one place. When you add authentication headers or better error handling, you change <code>APIClient</code>, and every service picks it up. Nothing changes for the view models: they still depend on <code>ProductService</code> and <code>CartService</code>, and previews and tests still use the same mocks.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">How the Layers Fit Together, and the Names I Use</h2>



<p class="wp-block-paragraph">Now that you&#8217;ve seen services, here&#8217;s how all the layers fit together. A quick note on naming: words like &#8220;view model,&#8221; &#8220;service,&#8221; and &#8220;repository&#8221; mean different things to different people, and you&#8217;ll find other definitions in other articles and codebases. A common one: many people call something a &#8220;service&#8221; that holds UI state and the methods that change it. In my naming, that&#8217;s a view model. If it holds UI state and is <code>@Observable</code> so views can react to it, it&#8217;s the UI backing layer, whatever its name says. A service, in contrast, never holds UI state.</p>



<p class="wp-block-paragraph">This is my take: the split and the names I&#8217;ve found most practical in SwiftUI apps.</p>



<figure class="wp-block-table"><table><thead><tr><th class="has-text-align-left" data-align="left">Layer</th><th class="has-text-align-left" data-align="left">Job</th><th class="has-text-align-left" data-align="left">Swift shape</th></tr></thead><tbody><tr><td class="has-text-align-left" data-align="left"><strong>View</strong></td><td class="has-text-align-left" data-align="left">Maps state to pixels, sends user intent</td><td class="has-text-align-left" data-align="left"><code>struct</code> conforming to <code>View</code></td></tr><tr><td class="has-text-align-left" data-align="left"><strong>View model</strong></td><td class="has-text-align-left" data-align="left">Owns UI state, mutates it consistently</td><td class="has-text-align-left" data-align="left"><code>@MainActor @Observable final class</code></td></tr><tr><td class="has-text-align-left" data-align="left"><strong>Model</strong></td><td class="has-text-align-left" data-align="left">Data and its intrinsic rules</td><td class="has-text-align-left" data-align="left"><code>struct</code></td></tr><tr><td class="has-text-align-left" data-align="left"><strong>Service</strong></td><td class="has-text-align-left" data-align="left">Helper worker: stateless functions for shared external dependencies like the network, file system, UserDefaults, or HealthKit. Reusable across view models, easy to mock.</td><td class="has-text-align-left" data-align="left"><code>nonisolated struct</code> with <code>@concurrent</code> functions</td></tr><tr><td class="has-text-align-left" data-align="left"><strong>Repository</strong></td><td class="has-text-align-left" data-align="left">Mutable state the UI doesn&#8217;t observe, like a cache or a token</td><td class="has-text-align-left" data-align="left"><code>actor</code> </td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>The data flow:</strong> user taps → view calls a view model method → service works in the background → data comes back → view model updates UI state on the main actor → SwiftUI updates the view.</p>


<div class="gb-container gb-container-50e6208d">

<figure class="gb-block-image gb-block-image-41c21b75"><img loading="lazy" decoding="async" width="961" height="649" class="gb-image gb-image-41c21b75" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swift-3.webp" alt="dependency injection in swift with multiple layers of abstraction" title="dependency-injection-swift-3" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swift-3.webp 961w, https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swift-3-300x203.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/10/dependency-injection-swift-3-768x519.webp 768w" sizes="auto, (max-width: 961px) 100vw, 961px" /></figure>

</div>


<p class="wp-block-paragraph">The dependencies point one way: views talk to view models, and view models talk to services. A view never calls a service directly. If it did, the view model&#8217;s state would no longer reflect what happened, and the data flow would be hard to follow.</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Wrap-Up</h2>



<p class="wp-block-paragraph">We started with a practical goal: view models you can preview and test without touching <code>UserDefaults</code> or the network. The tool that got us there was the Dependency Inversion Principle. The view model depends on a protocol, the live service is the default, and previews and tests pass in a mock.</p>



<p class="wp-block-paragraph">But testability wasn&#8217;t the only thing we gained along the way:</p>



<ul class="wp-block-list">
<li><strong>Reusable components.</strong> Services can be shared by several view models, and an <code>APIClient</code> keeps networking logic in one place.</li>



<li><strong>Separation of concerns.</strong> The view model manages UI state, and the service handles the shared external dependency. Each has one job.</li>



<li><strong>Clear boundaries.</strong> Dependencies point one way, from view to view model to service, so you always know where code belongs and how data flows.</li>
</ul>



<p class="wp-block-paragraph"><strong>What&#8217;s next:</strong> in this post, every dependency came in through the initializer. In a real SwiftUI app, the next question is how dependencies get from the app&#8217;s entry point to every view model that needs them, especially shared ones. That&#8217;s where the SwiftUI environment comes in, and it&#8217;s the topic of SwiftUI Dependency Injection: Initializer, Environment, or Container?</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer"></div>



<h5 class="wp-block-heading">Further Reading</h5>



<ul class="wp-block-list">
<li><a href="https://www.swiftyplace.com/blog/swiftui-mvvm" data-type="link" data-id="https://www.swiftyplace.com/blog/swiftui-mvvm">What Is a View Model in SwiftUI, Really?</a>: the definition of the UI backing layer this post builds on.</li>



<li><a href="https://www.swiftyplace.com/blog/mvvm-what-in-viewmodel" data-type="link" data-id="https://www.swiftyplace.com/blog/mvvm-what-in-viewmodel">What Should Go in a View Model?</a>: how to keep view models focused on one job.</li>



<li><a href="https://www.swiftyplace.com/blog/swiftui-architecture-swift-concurrency">How I Architect SwiftUI Apps for Swift Concurrency – So the Compiler Stays Quiet</a>: @MainActor, @concurrent, and Sendable: why view models live on the main actor and services run in the background.</li>
</ul>


<div class="gb-container gb-container-c5dedc2e">
<div class="gb-container gb-container-f7a433c7">
<div class="gb-container gb-container-7a8dc7a3">

<figure class="gb-block-image gb-block-image-f04fbbad"><a href="https://www.swiftyplace.com/free-swiftui-layout-cookbook" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" width="1446" height="1552" class="gb-image gb-image-f04fbbad" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm.webp" alt="" title="lead magnet mvvm" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm.webp 1446w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-280x300.webp 280w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-954x1024.webp 954w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-768x824.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-1431x1536.webp 1431w" sizes="auto, (max-width: 1446px) 100vw, 1446px" /></a></figure>

</div>

<div class="gb-container gb-container-98352fe6">

<h4 class="gb-headline gb-headline-4aacd94c gb-headline-text">Get the MVVM SwiftUI Cheat Sheet</h4>



<p class="gb-headline gb-headline-5e6c4f85 gb-headline-text">The cheat sheet puts the whole system on a few pages: what goes in a view model, which view owns it, how to pass it down the tree, common mistakes, and code skeletons you can copy.</p>


<div class="gb-container gb-container-34a8ad02">

<a class="gb-button gb-button-63e90e76 gb-button-blue" href="https://school.swiftyplace.com/f/swiftui-mvvm-cheat-sheet" target="_blank" rel="noopener noreferrer"><span class="gb-button-text">Get the free cheat sheet</span><span class="gb-icon"><svg aria-hidden="true" role="img" height="1em" width="1em" viewBox="0 0 256 512" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M224.3 273l-136 136c-9.4 9.4-24.6 9.4-33.9 0l-22.6-22.6c-9.4-9.4-9.4-24.6 0-33.9l96.4-96.4-96.4-96.4c-9.4-9.4-9.4-24.6 0-33.9L54.3 103c9.4-9.4 24.6-9.4 33.9 0l136 136c9.5 9.4 9.5 24.6.1 34z"></path></svg></span></a>

</div>
</div>
</div>
</div><p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/dependency-injection-swift">Dependency Injection in Swift: Services, Protocols, and Testable View Models</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.swiftyplace.com/blog/dependency-injection-swift/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>What Should Go in a View Model in SwiftUI?</title>
		<link>https://www.swiftyplace.com/blog/mvvm-what-in-viewmodel?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mvvm-what-in-viewmodel</link>
					<comments>https://www.swiftyplace.com/blog/mvvm-what-in-viewmodel#respond</comments>
		
		<dc:creator><![CDATA[Karin Prater]]></dc:creator>
		<pubDate>Mon, 26 Oct 2026 07:50:56 +0000</pubDate>
				<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Architecture]]></category>
		<guid isPermaLink="false">https://www.swiftyplace.com/?p=1005772</guid>

					<description><![CDATA[<p>How to use MVVM with SwiftUI? A practical guide to separation of concerns in MVVM, with real examples, code smells, and a checklist you can use today.</p>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/mvvm-what-in-viewmodel">What Should Go in a View Model in SwiftUI?</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Separation of concerns is the whole reason MVVM exists. Each layer gets one job: the view describes what the user sees, the view model manages the state behind it, and the layers below deal with data and the outside world. When every piece of code sits in the layer whose job it is, you know where to look, changes stay local, and one feature doesn&#8217;t break another.</p>



<p class="wp-block-paragraph">In <a href="https://www.swiftyplace.com/blog/swiftui-mvvm" data-type="link" data-id="https://www.swiftyplace.com/blog/swiftui-mvvm">What Is a View Model in SwiftUI, Really?</a>, we defined the view model&#8217;s concern: it owns UI state and is responsible for mutating that state properly and consistently.</p>



<p class="wp-block-paragraph">But adding a view model doesn&#8217;t give you separation of concerns on its own. It just gives you another place to put code. And it&#8217;s a very convenient place: it&#8217;s already connected to the view, it already has state, so one more property or one more method is always the easiest option. Do that for a few months, and the mess that used to live in your view now lives in your view model. You haven&#8217;t separated anything. You&#8217;ve moved it.</p>



<p class="wp-block-paragraph">It goes wrong in the other direction too. Logic that belongs in the view model stays in the view, and the view starts reaching in and changing the view model&#8217;s state piece by piece. Or UI code drifts into the view model, and you can no longer find what&#8217;s on screen by looking at the view.</p>



<p class="wp-block-paragraph">So once <a href="https://www.swiftyplace.com/blog/mvvm-view-model-use-case" target="_blank" data-type="link" data-id="https://www.swiftyplace.com/blog/mvvm-view-model-use-case" rel="noreferrer noopener">you&#8217;ve decided you need a view model</a>, the real question is where its boundaries are. In this post, I&#8217;ll show you how to define a view model&#8217;s job, what belongs inside it and what doesn&#8217;t, and how to spot code that sits in the wrong layer, with examples from a Markdown app, a product browser, a checkout flow, and an auth flow.</p>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Define the Job: One View Model per Use Case</h2>



<p class="wp-block-paragraph">The first decision isn&#8217;t about individual properties. It&#8217;s about the boundary of the view model itself. Before you add anything, ask: <strong>what is the job of this view model?</strong> What is it responsible for? Once that&#8217;s clear, you give it all the state, the methods, and the dependencies it needs to do that job, and nothing more.</p>



<p class="wp-block-paragraph">I think of this as scoping view models by <strong>use case</strong>: one coherent job around one set of state. The state and the methods that mutate it form a unit. They have a reason to live together. When you start adding a different set of state, with methods that have nothing to do with what&#8217;s already there, you&#8217;re mixing concerns. The view model loses its cohesion: the things inside it no longer have a logical reason to be in the same place.</p>



<p class="wp-block-paragraph">Let&#8217;s go back to the Markdown app from <a href="https://www.swiftyplace.com/blog/mvvm-view-model-use-case" data-type="link" data-id="https://www.swiftyplace.com/blog/mvvm-view-model-use-case">the previous post</a>. It has two clear use cases:</p>



<ul class="wp-block-list">
<li><strong>Themes:</strong> all available themes, which one is selected, and creating, deleting, selecting, and saving them.</li>



<li><strong>Documents:</strong> the list of Markdown documents, and loading, creating, renaming, and deleting them.</li>
</ul>



<figure class="gb-block-image gb-block-image-fb29cd7d"><img loading="lazy" decoding="async" width="2270" height="1079" class="gb-image gb-image-fb29cd7d" src="http://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-2-1.webp" alt="markdown ios app with MVVM in SwiftUI" title="when-to-use-viewmodel-example-1-2 1" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-2-1.webp 2270w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-2-1-300x143.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-2-1-1024x487.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-2-1-768x365.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-2-1-1536x730.webp 1536w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-2-1-2048x973.webp 2048w" sizes="auto, (max-width: 2270px) 100vw, 2270px" /></figure>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">So the app gets two view models, one for each:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@Observable class ThemeStore {
    private(set) var themes: &#91;Theme&#93; = []
    private(set) var selectedThemeID: Theme.ID?

    var selectedTheme: Theme? {
        themes.first { $0.id == selectedThemeID }
    }

    func createTheme(name: String, colors: ThemeColors) async { /* ... */ }
    func deleteTheme(_ theme: Theme) async { /* ... */ }
    func selectTheme(_ theme: Theme) async { /* ... */ }
}

@Observable class DocumentStore {
    private(set) var documents: &#91;MarkdownDocument&#93; = []

    func loadDocuments() async { /* ... */ }
    func createDocument(title: String) async { /* ... */ }
    func renameDocument(_ document: MarkdownDocument, to title: String) async { /* ... */ }
    func deleteDocument(_ document: MarkdownDocument) async { /* ... */ }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@Observable</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ThemeStore</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> themes: &#91;Theme&#93; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> selectedThemeID: Theme.ID</span><span style="color: #F286C4">?</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> selectedTheme: Theme</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        themes.</span><span style="color: #97E1F1">first</span><span style="color: #F6F6F4"> { </span><span style="color: #BF9EEE; font-style: italic">$0</span><span style="color: #F6F6F4">.id </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> selectedThemeID }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">createTheme</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">name</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">, </span><span style="color: #62E884; font-style: italic">colors</span><span style="color: #F6F6F4">: ThemeColors) </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> { </span><span style="color: #7B7F8B">/* ... */</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">deleteTheme</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">theme</span><span style="color: #F6F6F4">: Theme) </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> { </span><span style="color: #7B7F8B">/* ... */</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">selectTheme</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">theme</span><span style="color: #F6F6F4">: Theme) </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> { </span><span style="color: #7B7F8B">/* ... */</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">@Observable</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">DocumentStore</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> documents: &#91;MarkdownDocument&#93; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">loadDocuments</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> { </span><span style="color: #7B7F8B">/* ... */</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">createDocument</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">title</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> { </span><span style="color: #7B7F8B">/* ... */</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">renameDocument</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">document</span><span style="color: #F6F6F4">: MarkdownDocument, </span><span style="color: #62E884">to</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">title</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> { </span><span style="color: #7B7F8B">/* ... */</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">deleteDocument</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">document</span><span style="color: #F6F6F4">: MarkdownDocument) </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> { </span><span style="color: #7B7F8B">/* ... */</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Why not put both into one <code>AppViewModel</code>? Because themes and documents don&#8217;t change together. Deleting a document has nothing to do with which theme is selected. Creating a theme has nothing to do with the document list. They&#8217;re separate state, with separate mutations, so they live in separate view models.</p>



<p class="wp-block-paragraph">And here&#8217;s the interesting part: both are used on the same screen. The document detail view shows the document&#8217;s content and renders it with the selected theme. That&#8217;s fine. A view can use more than one view model:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);--cbp-line-highlight-color:rgba(251, 251, 239, 0.2);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ContentView: View {
    @State private var themeStore = ThemeStore()  
    @State private var documentStore = DocumentStore()
    @State private var selectedFile: MarkdownFile? = nil
    
    var body: some View {
        NavigationSplitView {
            MarkdownFilesListView(documentStore: documentStore, 
                                  selection: $selectedFile)
        } detail: {
            if let selectedFile {
                MarkdownDetailView(themeStore: themeStore,
                                   markdown: selectedFile)
            } else {
                PlaceholderView()
            }
        }
        .task {
           await themeStore.load()
           await documentStore.load()
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ContentView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> themeStore </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ThemeStore</span><span style="color: #F6F6F4">()  </span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> documentStore </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">DocumentStore</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> selectedFile: MarkdownFile</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">nil</span></span>
<span class="line"><span style="color: #F6F6F4">    </span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">NavigationSplitView</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">MarkdownFilesListView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">documentStore</span><span style="color: #F6F6F4">: documentStore, </span></span>
<span class="line"><span style="color: #F6F6F4">                                  </span><span style="color: #97E1F1">selection</span><span style="color: #F6F6F4">: $selectedFile)</span></span>
<span class="line"><span style="color: #F6F6F4">        } </span><span style="color: #97E1F1">detail</span><span style="color: #F6F6F4">: {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> selectedFile {</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">MarkdownDetailView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">themeStore</span><span style="color: #F6F6F4">: themeStore,</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">                                   </span><span style="color: #97E1F1">markdown</span><span style="color: #F6F6F4">: selectedFile)</span></span>
<span class="line"><span style="color: #F6F6F4">            } </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">PlaceholderView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">task</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">           </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> themeStore.</span><span style="color: #97E1F1">load</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">           </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> documentStore.</span><span style="color: #97E1F1">load</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">This is also why &#8220;one view model per screen&#8221; doesn&#8217;t work. The <code>MarkdownDetailView</code> screen needs state from two use cases. A single screen view model would either duplicate the theme state, or pull both use cases into one class. The use case decides the boundary, not the screen.</p>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Avoid the God View Model</h2>



<p class="wp-block-paragraph">Think about it this way. If you avoid spaghetti code in your views, but then move everything into one giant view model, you haven&#8217;t solved anything. You&#8217;ve just moved the mess around. And it&#8217;s not a new problem. Whatever separation technique you use, there&#8217;s always a risk of creating something massive. UIKit had the infamous massive view controller. In SwiftUI, we can end up with massive views. And we can absolutely end up with massive view models too.</p>



<p class="wp-block-paragraph">The opposite of a focused view model is the <strong>god view model: one huge class that holds everything</strong>. Themes, documents, settings, user info, sync status, all in one place, with dozens of methods and a file you scroll forever.</p>



<p class="wp-block-paragraph">Nobody sets out to write one. It happens one feature at a time. The view model is already there and already connected to the views, so adding <em>&#8220;just one more thing&#8221;</em> is the easiest option. Repeat that for a few months, and you have a god view model.</p>



<p class="wp-block-paragraph">Here&#8217;s why it hurts:</p>



<ul class="wp-block-list">
<li><strong>Hard to understand:</strong> you can&#8217;t tell what any part of it is responsible for, or which methods touch which state.</li>



<li><strong>Changes ripple:</strong> a change for one feature can break another, because they share the same class and sometimes the same state.</li>



<li><strong>Everything depends on everything:</strong> every view that uses it is connected to all of it, even the parts it doesn&#8217;t need.</li>



<li><strong>Hard to test:</strong> to test one behavior, you have to set up the whole thing.</li>



<li><strong>Merge conflicts:</strong> if everyone on the team works in the same file, you&#8217;ll be resolving conflicts constantly.</li>
</ul>



<p class="wp-block-paragraph">The fix is the same idea as above: split by use case. Not by line count, and not by screen. If a group of state and the methods that change it form their own job, they get their own view model.</p>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">UI State: Collect State That Changes Together</h2>



<p class="wp-block-paragraph">Once you know the use case, the same idea works on a smaller scale. Inside a view model, group the state that changes together.</p>



<p class="wp-block-paragraph">Loading is the classic example. When <code>DocumentStore</code> loads documents, three pieces of state are involved:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>private(set) var isLoading = false
private(set) var errorMessage: String?
private(set) var documents: &#91;MarkdownDocument&#93; = []</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> isLoading </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">false</span></span>
<span class="line"><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> errorMessage: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F286C4">?</span></span>
<span class="line"><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> documents: &#91;MarkdownDocument&#93; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span></code></pre></div>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">These always change together. Start loading: set <code>isLoading</code>, clear the error. Success: store the documents, reset <code>isLoading</code>. Failure: set the error, reset <code>isLoading</code>. Every mutation has to remember to update all three correctly. Forget one, and you&#8217;re in a state that shouldn&#8217;t exist, like a spinner and an error message at the same time.</p>



<p class="wp-block-paragraph">So at the very least, keep these properties together and change them together in one place. Even better, model them as one value with an enum:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>enum LoadingState&lt;Value> {
    case idle
    case loading
    case loaded(Value)
    case failed(String)
}

private(set) var state: LoadingState&lt;&#91;MarkdownDocument&#93;> = .idle</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">enum</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">LoadingState</span><span style="color: #F6F6F4">&lt;</span><span style="color: #BF9EEE; font-style: italic">Value</span><span style="color: #F6F6F4">&gt; {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> idle</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> loading</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> loaded(</span><span style="color: #97E1F1; font-style: italic">Value</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> failed(</span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> state: LoadingState&lt;&#91;MarkdownDocument&#93;&gt; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .idle</span></span></code></pre></div>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Now only valid states are possible, and every transition is a single assignment. The same idea applies elsewhere: form fields belong together with their validation errors, and a selection belongs together with the list it refers to.</p>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">What Belongs in a View Model</h2>



<p class="wp-block-paragraph">With the boundaries in place, here&#8217;s what actually goes inside.</p>



<p class="wp-block-paragraph"><strong>UI state.</strong> The data your views need to render: the list of documents, the selected theme, the loading state, form input.</p>



<p class="wp-block-paragraph"><strong>Derived state.</strong> Values that can be calculated from other state should be computed properties, not stored copies. <code>selectedTheme</code> is computed from <code>themes</code> and <code>selectedThemeID</code>. If you stored it as a separate property, you&#8217;d have to update it every time either of those changes, and sooner or later you&#8217;d forget. Computed properties have nothing to keep in sync. Other examples: <code>canSubmit</code> in a form, <code>formattedTotal</code> in a cart.</p>



<p class="wp-block-paragraph"><strong>Mutations.</strong> The methods responsible for changing the state properly and consistently. Creating a theme means adding it, selecting it, and saving, every time, in that order. That sequence lives in one method, so no view has to know about it.</p>



<p class="wp-block-paragraph"><strong>Display formatting.</strong> Turning raw data into something ready to show: a formatted price, a relative date, a title combined from several fields. This is about <em>what</em> to show. <em>How</em> it looks is still up to the view.</p>



<p class="wp-block-paragraph"><strong>Gatekeeping.</strong> Answering &#8220;is this action allowed right now?&#8221; as state, for example <code>canSubmit</code> or <code>canDeleteTheme</code>. The view model decides whether something is allowed. The view decides that &#8220;not allowed&#8221; means a disabled button.</p>



<p class="wp-block-paragraph"><strong>Dependencies.</strong> The services the view model needs to do its job, like the file service for <code>ThemeStore</code> or a networking service for loading products. The view model calls them. It doesn&#8217;t do their work itself.</p>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">What Doesn&#8217;t Belong (and Where It Goes)</h2>



<p class="wp-block-paragraph">Just as important is what stays out. Each of these has a better home. This is my personal recommendation that is clear and relatively straightforward to follow.</p>



<p class="wp-block-paragraph"><strong>Layout, styling, and any UI code → the view.</strong> Fonts, colors, spacing, animations, which view to show for which state. The view model never says &#8220;show a red label here,&#8221; and it never contains view code itself. More on that in the next section.</p>



<p class="wp-block-paragraph"><strong>Data structures and intrinsic rules → the model.</strong> A <code>Theme</code> struct, a <code>MarkdownDocument</code>, the rule for what makes a valid email address or a maximum cart quantity. These rules belong to the data itself, no matter which view model uses them.</p>



<p class="wp-block-paragraph"><strong>State from another use case → another view model.</strong> Even if a view needs it. The document detail view needs the selected theme, but that doesn&#8217;t mean the theme belongs in <code>DocumentStore</code>. The view simply uses both.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h5 class="wp-block-heading">Services: The Layer Behind the View Model</h5>



<p class="wp-block-paragraph">A view model&#8217;s job is managing UI state. But to do that job, it often needs things outside your own code: the network, the file system,&nbsp;<code>UserDefaults</code>, the Keychain, HealthKit. These are shared external dependencies, and working with them is a different job. So that work goes into a service.</p>



<p class="wp-block-paragraph">A service is a helper worker:</p>



<ul class="wp-block-list">
<li><strong>Stateless:</strong>&nbsp;plain functions that do one kind of work, like fetching products or saving themes.</li>



<li><strong>Off the main actor:</strong>&nbsp;heavy work like requests and decoding doesn&#8217;t block the UI.</li>



<li><strong>Reusable:</strong>&nbsp;the same API call can serve several view models, like the cart and checkout.</li>



<li><strong>Replaceable:</strong>&nbsp;the view model depends on a protocol, so you can inject a mock for previews and tests.</li>
</ul>



<p class="wp-block-paragraph">The view model keeps the state and decides when to call the service. The service does the work and returns the data. I go deeper into services, repositories, and dependency injection in a separate blog post.</p>



<div style="height:23px" aria-hidden="true" class="wp-block-spacer"></div>



<h5 class="wp-block-heading">Navigation: Coordinators for Presentation State</h5>



<p class="wp-block-paragraph">Simple navigation stays in the view: the user taps a product, and a detail view is pushed. But sometimes logic decides where to go.</p>



<p class="wp-block-paragraph">Say a shopping app checks for discount offers when the user opens the shop. If the server returns an offer, a sheet should open. That&#8217;s three concerns at once:</p>



<ul class="wp-block-list">
<li><strong>Fetching the offers</strong>&nbsp;is networking → a service.</li>



<li><strong>Holding the offers</strong>&nbsp;is UI state → the view model.</li>



<li><strong>Opening the sheet</strong>&nbsp;is presentation state → neither of them.</li>
</ul>



<p class="wp-block-paragraph">Presentation state gets its own owner: a&nbsp;<strong>coordinator</strong>. It&#8217;s an&nbsp;<code>@Observable</code>&nbsp;class that owns the navigation path and which sheet is shown. It holds only state, never view code. The view model decides&nbsp;<em>that</em>&nbsp;the offer should be shown and tells the coordinator; the view maps the coordinator&#8217;s state to the actual sheet.</p>



<p class="wp-block-paragraph">Coordinators pay off in larger, more complex apps, especially when several developers work on different features. And there, they should&nbsp;<strong>always be nested</strong>: an app coordinator for the top-level flows, and a child coordinator per feature, like shop or checkout. A single coordinator for the whole app turns into the same god object we just got rid of: it knows every screen, every feature depends on it, and every change touches it. With nested coordinators, each flow owns only its own navigation. The concerns stay separated, dependencies stay local, and features are easy to split into modules.</p>



<p class="wp-block-paragraph">This pattern is often called MVVM-C, and there are different ways to implement it. I cover how I use it in detail in another blog post: Navigation with Coordinators.</p>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Going Too Far: UI Code in a View Model</h2>



<p class="wp-block-paragraph">It&#8217;s possible to swing too far in the other direction, and move things into the view model that clearly belong in the view. The most extreme version is putting actual view code into it.</p>



<p class="wp-block-paragraph">Imagine an <code>AuthManager</code> with three states: loading, an error, or a logged-in user. Now we add a <code>@ViewBuilder</code> function that returns the screen for each state:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@MainActor
@Observable
final class AuthManager {
    private(set) var state: AuthState = .loading

    @ViewBuilder
    func screenComponent() -> some View {
        switch state {
        case .loading: ProgressView()
        case .failed(let message): Text(message)
        case .loggedIn(let user): Text("Welcome, (user.name)")
        }
    }
}

struct HomeView: View {
    let authManager: AuthManager

    var body: some View {
        authManager.screenComponent()
            .padding()
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">AuthManager</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> state: AuthState </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .loading</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@ViewBuilder</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">screenComponent</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">switch</span><span style="color: #F6F6F4"> state {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> .loading</span><span style="color: #F286C4">:</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProgressView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> .</span><span style="color: #97E1F1">failed</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> message)</span><span style="color: #F286C4">:</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(message)</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> .</span><span style="color: #97E1F1">loggedIn</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> user)</span><span style="color: #F286C4">:</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Welcome, (user.name)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">HomeView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> authManager: AuthManager</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        authManager.</span><span style="color: #97E1F1">screenComponent</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">padding</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">This works. But the view is now &#8220;unemployed.&#8221; It&#8217;s just an empty container that does nothing. And that causes real problems:</p>



<ul class="wp-block-list">
<li><strong>You can&#8217;t find your UI.</strong> Open <code>HomeView</code>, and you can&#8217;t tell what&#8217;s on screen. If someone asks you to make the welcome text bold, it&#8217;s not there. You jump to <code>AuthManager</code>, look through the cases, figure out which one to change, and bounce between files for a one-line UI tweak.</li>



<li><strong>Reusability drops.</strong> Before, the coupling went one way: the view knew about the view model. Now the view model also knows how the UI looks. If you want the same auth logic with a different design somewhere else, you can&#8217;t, because the UI is baked into the observable.</li>



<li><strong>Testing gets hard.</strong> Testing a normal view model is easy: is the state loading, yes or no? Testing a function that returns <code>some View</code> means dealing with SwiftUI&#8217;s opaque types, a deeply nested <code>ConditionalContent</code> type that&#8217;s hard to assert on, and possibly spinning up SwiftUI just to run a unit test.</li>
</ul>



<p class="wp-block-paragraph">So here&#8217;s my rule that&#8217;s simple enough to actually follow: <strong>no UI code in your view models.</strong> No <code>some View</code>, no <code>@ViewBuilder</code>, nothing that describes how to draw pixels.</p>



<p class="wp-block-paragraph">That gives each side a clear job:</p>



<ul class="wp-block-list">
<li><strong>The view maps state to pixels.</strong> It decides what to show for a given state and how to style it.</li>



<li><strong>The view model manages what state the app is in.</strong> It handles the data, the logic, the service calls, and the state transitions. If a request fails with a &#8220;forbidden&#8221; error, the view model stores that error. Whether it shows up as an alert, an inline message, or a banner is the view&#8217;s decision.</li>
</ul>



<p class="wp-block-paragraph">With that rule, the switch moves back where it belongs:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct HomeView: View {
    let authManager: AuthManager

    var body: some View {
        switch authManager.state {
        case .loading:
            ProgressView()
        case .failed(let message):
            Text(message).foregroundStyle(.red)
        case .loggedIn(let user):
            Text("Welcome, (user.name)").font(.title)
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">HomeView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> authManager: AuthManager</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">switch</span><span style="color: #F6F6F4"> authManager.state {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> .loading</span><span style="color: #F286C4">:</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">ProgressView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> .</span><span style="color: #97E1F1">failed</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> message)</span><span style="color: #F286C4">:</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(message).</span><span style="color: #97E1F1">foregroundStyle</span><span style="color: #F6F6F4">(.red)</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> .</span><span style="color: #97E1F1">loggedIn</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> user)</span><span style="color: #F286C4">:</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Welcome, (user.name)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">).</span><span style="color: #97E1F1">font</span><span style="color: #F6F6F4">(.title)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Now everything you see on screen is in the view, and <code>AuthManager</code> is back to being a plain class you can test with simple assertions.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Example: What Stays Out of a Product Browser</h2>



<p class="wp-block-paragraph">Let&#8217;s put this into practice with a product browser. You can search through a list of products and apply filters to narrow down the results. There are network requests, filtering logic, loading states, and error handling, so all of that moves into a <code>ProductViewModel</code>.</p>


<div class="gb-container gb-container-cc9d7384">

<figure class="gb-block-image gb-block-image-b10aaae7"><img loading="lazy" decoding="async" width="1154" height="1152" class="gb-image gb-image-b10aaae7" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-what-inside-productbrowser.webp" alt="" title="mvvm-what-inside-productbrowser" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-what-inside-productbrowser.webp 1154w, https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-what-inside-productbrowser-300x300.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-what-inside-productbrowser-1024x1022.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-what-inside-productbrowser-150x150.webp 150w, https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-what-inside-productbrowser-768x767.webp 768w" sizes="auto, (max-width: 1154px) 100vw, 1154px" /></figure>

</div>


<p class="wp-block-paragraph">First, define the job. This view model fetches products, updates the list when the search or filter changes, manages the loading state, and keeps an error message the UI can show. To do that job, it needs the search query, the selected filter, the methods that perform the fetch, and the service that does the network request in the background:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@MainActor
@Observable
final class ProductViewModel {
    var searchQuery = ""
    var selectedFilter: ProductFilter = .all
    private(set) var state: LoadingState&lt;&#91;Product&#93;> = .idle

    private let productService: ProductService

    func fetchProducts() async { /* ... */ }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> searchQuery </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> selectedFilter: ProductFilter </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .all</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> state: LoadingState&lt;&#91;Product&#93;&gt; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .idle</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> productService: ProductService</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">fetchProducts</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> { </span><span style="color: #7B7F8B">/* ... */</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">That&#8217;s it. Now the interesting part is what I deliberately kept in the view:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ProductBrowserView: View {
    @State private var viewModel = ProductViewModel()
    @State private var isFilterSheetShown = false
    @State private var isGridLayout = true
    @State private var path = NavigationPath()

    // ...
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ProductBrowserView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ProductViewModel</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> isFilterSheetShown </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">false</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> isGridLayout </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">true</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> path </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">NavigationPath</span><span style="color: #F6F6F4">()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// ...</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<ul class="wp-block-list">
<li><strong>Whether the filter sheet is shown.</strong> Does the view model need to know a sheet is open to fetch products? No. It cares about <em>which</em> filter is selected, not whether the UI for choosing it is visible.</li>



<li><strong>Grid or list layout.</strong> A display preference. It has nothing to do with fetching or managing products.</li>



<li><strong>The navigation path.</strong> Does the view model need to know the user tapped through to a detail screen? No. If the detail screen needs more data, that&#8217;s a different job, with a different lifetime, and only needed once the user is actually there.</li>
</ul>



<p class="wp-block-paragraph">All three are about what&#8217;s currently on screen: display state, navigation state, interaction state. They have a different concern than the view model&#8217;s job, so they stay in the view.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Example: When Logic Should Move In</h2>



<p class="wp-block-paragraph">The opposite happens too: code that lives in the view but belongs to the view model&#8217;s job.</p>


<div class="gb-container gb-container-062ded38">

<figure class="gb-block-image gb-block-image-7698b8dc"><img loading="lazy" decoding="async" width="566" height="1152" class="gb-image gb-image-7698b8dc" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-what-inside-shopping-cart.webp" alt="" title="mvvm-what-inside-shopping-cart" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-what-inside-shopping-cart.webp 566w, https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-what-inside-shopping-cart-147x300.webp 147w, https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-what-inside-shopping-cart-503x1024.webp 503w" sizes="auto, (max-width: 566px) 100vw, 566px" /></figure>

</div>


<p class="wp-block-paragraph">Say a shopping app has a checkout flow. A&nbsp;<code>CheckoutViewModel</code>&nbsp;loads the final cart so the user can review it: the items, subtotal, discount, shipping, taxes, and total. Its job is to manage those totals.</p>



<p class="wp-block-paragraph">Then a new feature request comes in: the user should be able to enter a promo code. In a first version, the promo code logic lives in the view. To make that work, the view model&#8217;s totals have to be settable from outside:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);--cbp-line-highlight-color:rgba(251, 251, 239, 0.2);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@MainActor
@Observable
final class CheckoutViewModel {
    var subtotal: Decimal = 0
    var discount: Decimal = 0
    var shipping: Decimal = 0
    var taxes: Decimal = 0
    var total: Decimal = 0
    // ...
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">CheckoutViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> subtotal: Decimal </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> discount: Decimal </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> shipping: Decimal </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> taxes: Decimal </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> total: Decimal </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// ...</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">And the view does the work:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);--cbp-line-highlight-color:rgba(251, 251, 239, 0.2);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct CheckoutView: View {
    var checkoutViewModel: CheckoutViewModel
    @State private var promoCode = ""
    @State private var promoError: String?

    var body: some View {
        Form {
            CartSummarySection(checkoutViewModel: checkoutViewModel)
            Section("Promo Code") {
                TextField("Enter code", text: $promoCode)
                if let promoError {
                    Text(promoError).foregroundStyle(.red)
                }
                Button("Apply") { applyPromoCode() }
            }
        }
    }

    // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a0.png" alt="⚠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Business logic in the view
    private func applyPromoCode() {
        guard promoCode == promoCode.uppercased() else {
            promoError = "Promo codes use capital letters only."
            return
        }

        if promoCode == "SAVE10" {
            // Reads subtotal, changes discount...
            checkoutViewModel.discount = checkoutViewModel.subtotal * 0.1
            // ...then reads three more values to change total
            checkoutViewModel.total = checkoutViewModel.subtotal
                - checkoutViewModel.discount
                + checkoutViewModel.shipping
                + checkoutViewModel.taxes // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a0.png" alt="⚠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> taxes were calculated before the discount
            promoError = nil
        } else {
            promoError = "This code isn't valid."
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">CheckoutView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> checkoutViewModel: CheckoutViewModel</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> promoCode </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> promoError: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F286C4">?</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Form</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">CartSummarySection</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">checkoutViewModel</span><span style="color: #F6F6F4">: checkoutViewModel)</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Section</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Promo Code</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">TextField</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Enter code</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">text</span><span style="color: #F6F6F4">: $promoCode)</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> promoError {</span></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(promoError).</span><span style="color: #97E1F1">foregroundStyle</span><span style="color: #F6F6F4">(.red)</span></span>
<span class="line"><span style="color: #F6F6F4">                }</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">Button</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Apply</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) { </span><span style="color: #97E1F1">applyPromoCode</span><span style="color: #F6F6F4">() }</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// &#x26a0; Business logic in the view</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">applyPromoCode</span><span style="color: #F6F6F4">() {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">guard</span><span style="color: #F6F6F4"> promoCode </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> promoCode.</span><span style="color: #97E1F1">uppercased</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            promoError </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Promo codes use capital letters only.</span><span style="color: #DEE492">&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">return</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> promoCode </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">SAVE10</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4"> {</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">            </span><span style="color: #7B7F8B">// Reads subtotal, changes discount...</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">            checkoutViewModel.discount </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> checkoutViewModel.subtotal </span><span style="color: #F286C4">*</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0.1</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">            </span><span style="color: #7B7F8B">// ...then reads three more values to change total</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">            checkoutViewModel.total </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> checkoutViewModel.subtotal</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">                </span><span style="color: #F286C4">-</span><span style="color: #F6F6F4"> checkoutViewModel.discount</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">                </span><span style="color: #F286C4">+</span><span style="color: #F6F6F4"> checkoutViewModel.shipping</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">                </span><span style="color: #F286C4">+</span><span style="color: #F6F6F4"> checkoutViewModel.taxes </span><span style="color: #7B7F8B">// &#x26a0; taxes were calculated before the discount</span></span>
<span class="line"><span style="color: #F6F6F4">            promoError </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">nil</span></span>
<span class="line"><span style="color: #F6F6F4">        } </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            promoError </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">This code isn&#39;t valid.</span><span style="color: #DEE492">&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Look at what&nbsp;<code>applyPromoCode()</code>&nbsp;does with the view model. It reads&nbsp;<code>subtotal</code>, changes&nbsp;<code>discount</code>, then reads&nbsp;<code>subtotal</code>,&nbsp;<code>discount</code>,&nbsp;<code>shipping</code>, and&nbsp;<code>taxes</code>&nbsp;again to change&nbsp;<code>total</code>. The view has to know how the totals depend on each other, and it gets it wrong: the taxes were calculated on the old subtotal, so the user sees a wrong total. And the valid codes are hardcoded in the view, when only the server knows which codes exist.</p>



<p class="wp-block-paragraph">That&#8217;s the code smell to watch for:&nbsp;<strong>if your view reads one property from the view model, changes another, then reads a third, it&#8217;s working with the view model&#8217;s internals.</strong>&nbsp;That&#8217;s a sign the view is handling a responsibility that belongs to the view model.</p>



<p class="wp-block-paragraph">And look at the job again: managing the totals. Applying a promo code is part of that job. So it moves in, behind a single method. The server validates the code and returns the recalculated cart, and the view model updates all totals together:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);--cbp-line-highlight-color:rgba(251, 251, 239, 0.2);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@MainActor
@Observable
final class CheckoutViewModel {
    private(set) var items: &#91;CartItem&#93; = []
    private(set) var subtotal: Decimal = 0
    private(set) var discount: Decimal = 0
    private(set) var shipping: Decimal = 0
    private(set) var taxes: Decimal = 0
    private(set) var total: Decimal = 0

    private(set) var isApplyingPromoCode = false
    private(set) var promoCodeError: String?

    private let cartService: CartService

    init(cartService: CartService) {
        self.cartService = cartService
    }

    func loadCart() async {
        // Fetch the final cart and call update(with:)
    }

    func applyPromoCode(_ code: String) async {
        isApplyingPromoCode = true
        promoCodeError = nil
        defer { isApplyingPromoCode = false }

        do {
            // The server validates the code and returns recalculated totals
            let cart = try await cartService.applyPromoCode(code)
            update(with: cart)
        } catch {
            promoCodeError = "This promo code isn't valid."
        }
    }

    // All totals change together, in one place
    private func update(with cart: Cart) {
        items = cart.items
        subtotal = cart.subtotal
        discount = cart.discount
        shipping = cart.shipping
        taxes = cart.taxes
        total = cart.total
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">CheckoutViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> items: &#91;CartItem&#93; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> subtotal: Decimal </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> discount: Decimal </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> shipping: Decimal </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> taxes: Decimal </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> total: Decimal </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> isApplyingPromoCode </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">false</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> promoCodeError: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F286C4">?</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> cartService: CartService</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">cartService</span><span style="color: #F6F6F4">: CartService) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.cartService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> cartService</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">loadCart</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #7B7F8B">// Fetch the final cart and call update(with:)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">applyPromoCode</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">code</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">        isApplyingPromoCode </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">true</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">        promoCodeError </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">nil</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">defer</span><span style="color: #F6F6F4"> { isApplyingPromoCode </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">false</span><span style="color: #F6F6F4"> }</span></span>
<span class="line cbp-line-highlight"></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">do</span><span style="color: #F6F6F4"> {</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">            </span><span style="color: #7B7F8B">// The server validates the code and returns recalculated totals</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> cart </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> cartService.</span><span style="color: #97E1F1">applyPromoCode</span><span style="color: #F6F6F4">(code)</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">update</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">with</span><span style="color: #F6F6F4">: cart)</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">        } </span><span style="color: #F286C4">catch</span><span style="color: #F6F6F4"> {</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">            promoCodeError </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">This promo code isn&#39;t valid.</span><span style="color: #DEE492">&quot;</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">        }</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// All totals change together, in one place</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">update</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">with</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">cart</span><span style="color: #F6F6F4">: Cart) {</span></span>
<span class="line"><span style="color: #F6F6F4">        items </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> cart.items</span></span>
<span class="line"><span style="color: #F6F6F4">        subtotal </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> cart.subtotal</span></span>
<span class="line"><span style="color: #F6F6F4">        discount </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> cart.discount</span></span>
<span class="line"><span style="color: #F6F6F4">        shipping </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> cart.shipping</span></span>
<span class="line"><span style="color: #F6F6F4">        taxes </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> cart.taxes</span></span>
<span class="line"><span style="color: #F6F6F4">        total </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> cart.total</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The totals are&nbsp;<code>private(set)</code>&nbsp;again, so no view can change one without the others. The view just hands off the code and shows the state:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>Button("Apply Promo Code") {
    Task { await checkoutViewModel.applyPromoCode(promoCode) }
}
.disabled(checkoutViewModel.isApplyingPromoCode)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #97E1F1">Button</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Apply Promo Code</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">Task</span><span style="color: #F6F6F4"> { </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> checkoutViewModel.</span><span style="color: #97E1F1">applyPromoCode</span><span style="color: #F6F6F4">(promoCode) }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">disabled</span><span style="color: #F6F6F4">(checkoutViewModel.isApplyingPromoCode)</span></span></code></pre></div>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Notice that&nbsp;<code>promoCode</code>&nbsp;stays in the view as&nbsp;<code>@State</code>. It&#8217;s plain text input that only this view uses, until the user taps Apply. What moved is the logic that changes the totals.</p>



<p class="wp-block-paragraph">And there&#8217;s a bonus: if promo codes can be applied in several places in the app, that logic now lives in one place instead of being duplicated across views.</p>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">A Quick Checklist</h2>



<p class="wp-block-paragraph">When you&#8217;re about to add something to a view model, run through these questions:</p>



<ol class="wp-block-list">
<li><strong>What&#8217;s the job of this view model?</strong> Does the new code belong to that job? If it&#8217;s part of a different job, it belongs in a different view model.</li>



<li><strong>Does it own or change UI state?</strong> If not, move it to the view, the model, or a service.</li>



<li><strong>Is it UI code?</strong> No <code>some View</code>, no <code>@ViewBuilder</code>. That stays in the view.</li>



<li><strong>Does it change together with the rest of the state here?</strong> If yes, keep it close, and update it in the same place.</li>



<li><strong>Can it be derived instead of stored?</strong> Then make it a computed property.</li>



<li><strong>Are several related properties really one state?</strong> Then consider modeling them as one enum.</li>



<li><strong>Is the view reaching into several view model properties to make one change?</strong> Then that logic belongs in the view model, behind a single method.</li>
</ol>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Wrapping Up</h2>



<p class="wp-block-paragraph">A good view model is focused. It has one clear job, holds the state that changes together, and is responsible for mutating that state properly and consistently. Everything else has a better home: UI code and display state in the view, rules in the model, heavy work in services, and other jobs in their own view models.</p>



<p class="wp-block-paragraph">This isn&#8217;t a decision you make once. As your app grows and new features arrive, keep asking whether new code belongs to an existing view model&#8217;s job. Sometimes logic needs to move out, like the filter sheet in the product browser. Sometimes it needs to move in, like the promo code in checkout. The line stays the same: the view model manages state and logic, and the view maps that state to what the user sees.</p>


<div class="gb-container gb-container-c5dedc2e">
<div class="gb-container gb-container-f7a433c7">
<div class="gb-container gb-container-7a8dc7a3">

<figure class="gb-block-image gb-block-image-f04fbbad"><a href="https://www.swiftyplace.com/free-swiftui-layout-cookbook" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" width="1446" height="1552" class="gb-image gb-image-f04fbbad" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm.webp" alt="" title="lead magnet mvvm" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm.webp 1446w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-280x300.webp 280w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-954x1024.webp 954w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-768x824.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-1431x1536.webp 1431w" sizes="auto, (max-width: 1446px) 100vw, 1446px" /></a></figure>

</div>

<div class="gb-container gb-container-98352fe6">

<h4 class="gb-headline gb-headline-4aacd94c gb-headline-text">Get the MVVM SwiftUI Cheat Sheet</h4>



<p class="gb-headline gb-headline-5e6c4f85 gb-headline-text">The cheat sheet puts the whole system on a few pages: what goes in a view model, which view owns it, how to pass it down the tree, common mistakes, and code skeletons you can copy.</p>


<div class="gb-container gb-container-34a8ad02">

<a class="gb-button gb-button-63e90e76 gb-button-blue" href="https://school.swiftyplace.com/f/swiftui-mvvm-cheat-sheet" target="_blank" rel="noopener noreferrer"><span class="gb-button-text">Get the free cheat sheet</span><span class="gb-icon"><svg aria-hidden="true" role="img" height="1em" width="1em" viewBox="0 0 256 512" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M224.3 273l-136 136c-9.4 9.4-24.6 9.4-33.9 0l-22.6-22.6c-9.4-9.4-9.4-24.6 0-33.9l96.4-96.4-96.4-96.4c-9.4-9.4-9.4-24.6 0-33.9L54.3 103c9.4-9.4 24.6-9.4 33.9 0l136 136c9.5 9.4 9.5 24.6.1 34z"></path></svg></span></a>

</div>
</div>
</div>
</div>


<div style="height:45px" aria-hidden="true" class="wp-block-spacer"></div>



<h5 class="wp-block-heading">Further Reading</h5>



<ul class="wp-block-list">
<li class="has-f-6-f-6-f-4-color has-text-color"><a href="https://www.swiftyplace.com/blog/swiftui-mvvm" data-type="link" data-id="https://www.swiftyplace.com/blog/swiftui-mvvm">What Is a View Model in SwiftUI, Really?</a></li>



<li class="has-f-6-f-6-f-4-color has-text-color"><a href="https://www.swiftyplace.com/blog/mvvm-view-model-use-case">When to Use a View Model in SwiftUI (and When It’s Overkill)</a></li>
</ul>



<p class="wp-block-paragraph"></p>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/mvvm-what-in-viewmodel">What Should Go in a View Model in SwiftUI?</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.swiftyplace.com/blog/mvvm-what-in-viewmodel/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>When to Use a View Model in SwiftUI (and When It&#8217;s Overkill)</title>
		<link>https://www.swiftyplace.com/blog/mvvm-view-model-use-case?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mvvm-view-model-use-case</link>
					<comments>https://www.swiftyplace.com/blog/mvvm-view-model-use-case#respond</comments>
		
		<dc:creator><![CDATA[Karin Prater]]></dc:creator>
		<pubDate>Mon, 19 Oct 2026 07:58:16 +0000</pubDate>
				<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Architecture]]></category>
		<guid isPermaLink="false">https://www.swiftyplace.com/?p=1005743</guid>

					<description><![CDATA[<p>A view model is a powerful tool, but it’s also an extra file and an extra layer of abstraction. Through four practical examples, we’ll look at when a view model earns its place and when it’s just overblown, unnecessary code that gets in your way.</p>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/mvvm-view-model-use-case">When to Use a View Model in SwiftUI (and When It&#8217;s Overkill)</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In the previous post, we looked at <a href="https://www.swiftyplace.com/blog/swiftui-mvvm" data-type="post" data-id="1005742">what a view model</a> actually is: a UI backing layer that owns UI state and is responsible for mutating that state properly and consistently.</p>



<p class="wp-block-paragraph">That&#8217;s a powerful tool. But it&#8217;s also an extra file and an extra layer of abstraction. So the question isn&#8217;t &#8220;should I always use a view model?&#8221; The question is: when do the benefits outweigh the cost?</p>



<p class="wp-block-paragraph">In this post, I&#8217;ll walk you through four examples. I&#8217;ll show simple and complex versions so you can see exactly where a view model starts to make sense and where it becomes an overblown, unnecessary thing that gets in your way.</p>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">The Cost and the Benefit of View Model in MVVM</h2>



<p class="wp-block-paragraph">Before we get into the examples, let&#8217;s be clear about what we&#8217;re weighing.</p>



<p class="wp-block-paragraph"><strong>The cost of a view model:</strong></p>



<ul class="wp-block-list">
<li>Another file and another type to maintain</li>



<li>Your code is spread over two places</li>



<li>To find out what a view shows, you sometimes have to jump to another file</li>



<li>More objects for SwiftUI to manage</li>
</ul>



<p class="wp-block-paragraph"><strong>The benefit of a view model:</strong></p>



<ul class="wp-block-list">
<li>Views stay simple and focused on UI</li>



<li>State mutations live in one place and happen the same way every time</li>



<li>Several views can share the same state and the same methods to change it</li>



<li>State can outlive a single view</li>
</ul>



<p class="wp-block-paragraph">If a view model doesn&#8217;t deliver any of those benefits, you&#8217;re only paying the cost. Let&#8217;s see what that looks like in practice.</p>



<div style="height:45px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Example 1: From a Color Picker to a Theme Editor</h2>



<h3 class="wp-block-heading">The Simple Version</h3>



<p class="wp-block-paragraph">The first example is a simple document app. Each document is a short text snippet with its own color, and when you open a document, that color is used for the background. At the bottom, there&#8217;s a color picker for switching between colors.</p>


<div class="gb-container gb-container-0b026956">

<figure class="gb-block-image gb-block-image-15addc30"><img loading="lazy" decoding="async" width="1161" height="1143" class="gb-image gb-image-15addc30" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1.webp" alt="iOS app with document app. Simple version with a color picker for the document background. No view model needed. MVVM would be overkill in this example." title="when-to-use-viewmodel-example-1" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1.webp 1161w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-300x295.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-1024x1008.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-768x756.webp 768w" sizes="auto, (max-width: 1161px) 100vw, 1161px" /></figure>

</div>


<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Say you&#8217;re building an early MVP and want to keep things easy. You might just hardcode the available colors:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);--cbp-line-highlight-color:rgba(251, 251, 239, 0.2);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ColorPickerView: View {
    @Binding var selectedColor: Color

    let colors: &#91;Color&#93; = &#91;.red, .orange, .yellow, .green, .blue, .purple&#93;

    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack {
                ForEach(colors, id: .self) { color in
                    Circle()
                        .fill(color)
                        .frame(width: 32, height: 32)
                        .onTapGesture { selectedColor = color }
                }
            }
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ColorPickerView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Binding</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> selectedColor: Color</span></span>
<span class="line"></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> colors: &#91;Color&#93; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> &#91;.red, .orange, .yellow, .green, .blue, .purple&#93;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">ScrollView</span><span style="color: #F6F6F4">(.horizontal, </span><span style="color: #97E1F1">showsIndicators</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">false</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">HStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">ForEach</span><span style="color: #F6F6F4">(colors, </span><span style="color: #97E1F1">id</span><span style="color: #F6F6F4">: .</span><span style="color: #F286C4">self</span><span style="color: #F6F6F4">) { color </span><span style="color: #F286C4">in</span></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">Circle</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">                        .</span><span style="color: #97E1F1">fill</span><span style="color: #F6F6F4">(color)</span></span>
<span class="line"><span style="color: #F6F6F4">                        .</span><span style="color: #97E1F1">frame</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">width</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">32</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">height</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">32</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">                        .</span><span style="color: #97E1F1">onTapGesture</span><span style="color: #F6F6F4"> { selectedColor </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> color }</span></span>
<span class="line"><span style="color: #F6F6F4">                }</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The view has an array of colors and a horizontal scroll view that iterates over them. Tap a color, and it becomes the selected color through the binding. This view is almost entirely UI. There&#8217;s no logic here.</p>



<p class="wp-block-paragraph">So what would a view model look like? The only thing we could move into it is the array of colors:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@Observable
class ColorPickerStore {
    let colors: &#91;Color&#93; = &#91;.red, .orange, .yellow, .green, .blue, .purple&#93;
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ColorPickerStore</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> colors: &#91;Color&#93; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> &#91;.red, .orange, .yellow, .green, .blue, .purple&#93;</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">That&#8217;s it: an observable class holding a hardcoded array. It doesn&#8217;t own any state that changes, and it doesn&#8217;t take any work off the view. It just adds an extra layer and splits the code across two files. This is definitely overkill. I would stick with the view-only solution here.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">When the Requirements Change</h3>



<p class="wp-block-paragraph">Now let&#8217;s keep working on the app. Instead of using color just for the background, I want to render Markdown, with colors for the headings, the code blocks, and the document background. I also want users to create their own themes with custom colors and fonts, and those themes need to be saved to disk and loaded again the next time.</p>



<figure class="gb-block-image gb-block-image-31765222"><img loading="lazy" decoding="async" width="2270" height="1079" class="gb-image gb-image-31765222" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-2-1.webp" alt="iOS app with a Markdown document app in SwiftUI. Use of view model to store and retrieve themes for markdown rendering. Showing the MVVM pattern in SwiftUI" title="when-to-use-viewmodel-example-1-2 1" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-2-1.webp 2270w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-2-1-300x143.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-2-1-1024x487.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-2-1-768x365.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-2-1-1536x730.webp 1536w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-1-2-1-2048x973.webp 2048w" sizes="auto, (max-width: 2270px) 100vw, 2270px" /></figure>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The theme picker view itself still doesn&#8217;t have much logic. It&#8217;s mostly UI code: show this list, show this button, use this styling. The real work happens in a store (aka the view model):</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@MainActor
@Observable
final class ThemeStore {
    private(set) var themes: &#91;Theme&#93; = []
    private(set) var selectedThemeID: Theme.ID?

    var selectedTheme: Theme? {
        themes.first { $0.id == selectedThemeID }
    }

    private let fileService: ThemeFileService

    init(fileService: ThemeFileService = ThemeFileService()) {
        self.fileService = fileService
    }

    func loadThemes() async {
        themes = (try? await fileService.load()) ?? Theme.defaults
    }

    func createTheme(name: String, colors: ThemeColors) async {
        let theme = Theme(name: name, colors: colors)
        themes.append(theme)
        selectedThemeID = theme.id
        await save()
    }

    func deleteTheme(_ theme: Theme) async {
        themes.removeAll { $0.id == theme.id }
        await save()
    }

    func selectTheme(_ theme: Theme) async {
        selectedThemeID = theme.id
        await save()
    }

    private func save() async {
        try? await fileService.save(themes)
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ThemeStore</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> themes: &#91;Theme&#93; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> selectedThemeID: Theme.ID</span><span style="color: #F286C4">?</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> selectedTheme: Theme</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        themes.</span><span style="color: #97E1F1">first</span><span style="color: #F6F6F4"> { </span><span style="color: #BF9EEE; font-style: italic">$0</span><span style="color: #F6F6F4">.id </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> selectedThemeID }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> fileService: ThemeFileService</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">fileService</span><span style="color: #F6F6F4">: ThemeFileService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ThemeFileService</span><span style="color: #F6F6F4">()) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.fileService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> fileService</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">loadThemes</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        themes </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> (</span><span style="color: #F286C4">try?</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> fileService.</span><span style="color: #97E1F1">load</span><span style="color: #F6F6F4">()) </span><span style="color: #F286C4">??</span><span style="color: #F6F6F4"> Theme.defaults</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">createTheme</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">name</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">, </span><span style="color: #62E884; font-style: italic">colors</span><span style="color: #F6F6F4">: ThemeColors) </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> theme </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">Theme</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">name</span><span style="color: #F6F6F4">: name, </span><span style="color: #97E1F1">colors</span><span style="color: #F6F6F4">: colors)</span></span>
<span class="line"><span style="color: #F6F6F4">        themes.</span><span style="color: #97E1F1">append</span><span style="color: #F6F6F4">(theme)</span></span>
<span class="line"><span style="color: #F6F6F4">        selectedThemeID </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> theme.id</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">save</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">deleteTheme</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">theme</span><span style="color: #F6F6F4">: Theme) </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        themes.</span><span style="color: #97E1F1">removeAll</span><span style="color: #F6F6F4"> { </span><span style="color: #BF9EEE; font-style: italic">$0</span><span style="color: #F6F6F4">.id </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> theme.id }</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">save</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">selectTheme</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">theme</span><span style="color: #F6F6F4">: Theme) </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        selectedThemeID </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> theme.id</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">save</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">save</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">try?</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> fileService.</span><span style="color: #97E1F1">save</span><span style="color: #F6F6F4">(themes)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Now there&#8217;s real state to manage: all the themes and which one is selected. And there are real mutations. When I create a theme, it needs to be added, selected, and saved. When I delete one, the UI state has to update and the change has to be saved for next time. Because every mutation goes through the store, each one ends with the same <code>save()</code> call, and nothing gets forgotten.</p>



<p class="wp-block-paragraph">Notice that the store doesn&#8217;t do the file handling itself. Encoding and decoding all the themes into a JSON file in the documents directory is quite a bit of code, and it has nothing to do with UI state. So that work goes to a separate service that runs in the background. That keeps the store small and focused. I cover this layer in more detail in another post about Services and Repositories.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Where the Store Lives</h3>



<p class="wp-block-paragraph">There&#8217;s one more reason the store pays off here. The themes are created and managed in the theme picker sheet, but the selected theme is also needed in the view that renders every Markdown file.</p>



<p class="wp-block-paragraph">If the store lived inside the sheet or the detail view, it would be created and thrown away every time I navigate back and forth, and the themes would have to be reloaded each time. So I place it at the app&#8217;s top level, where it lives as long as the themes are needed, and pass it to every view that uses it.</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ContentView: View {
    // owned high in the view tree, 
    // lifes for the duration of the app
    @State private var themeStore = ThemeStore()  
    @State private var markdownFileStore = MarkdownFileStore()
    @State private var selectedFile: MarkdownFile? = nil
    
    var body: some View {
        NavigationSplitView {
            MarkdownFilesListView(markdownFileStore: markdownFileStore, 
                                  selection: $selectedFile)
        } detail: {
            if let selectedFile {
                MarkdownDetailView(themeStore: themeStore,
                                   markdown: selectedFile)
            } else {
                PlaceholderView()
            }
        }
        .task {
           await themeStore.load()
           await markdownFileStore.load()
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ContentView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// owned high in the view tree, </span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// lifes for the duration of the app</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> themeStore </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ThemeStore</span><span style="color: #F6F6F4">()  </span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> markdownFileStore </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">MarkdownFileStore</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> selectedFile: MarkdownFile</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">nil</span></span>
<span class="line"><span style="color: #F6F6F4">    </span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">NavigationSplitView</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">MarkdownFilesListView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">markdownFileStore</span><span style="color: #F6F6F4">: markdownFileStore, </span></span>
<span class="line"><span style="color: #F6F6F4">                                  </span><span style="color: #97E1F1">selection</span><span style="color: #F6F6F4">: $selectedFile)</span></span>
<span class="line"><span style="color: #F6F6F4">        } </span><span style="color: #97E1F1">detail</span><span style="color: #F6F6F4">: {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> selectedFile {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">MarkdownDetailView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">themeStore</span><span style="color: #F6F6F4">: themeStore,</span></span>
<span class="line"><span style="color: #F6F6F4">                                   </span><span style="color: #97E1F1">markdown</span><span style="color: #F6F6F4">: selectedFile)</span></span>
<span class="line"><span style="color: #F6F6F4">            } </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">PlaceholderView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">task</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">           </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> themeStore.</span><span style="color: #97E1F1">load</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">           </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> markdownFileStore.</span><span style="color: #97E1F1">load</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">And because all the logic is in one neat package, I can move it wherever I need it later. If the loading code were scattered across views, every change would mean moving a lot more code around.</p>



<p class="wp-block-paragraph"><strong>Takeaway:</strong> same feature, different answer. The simple color picker had nothing to manage. The theme editor has state that changes, mutations that need to happen consistently, and several views that need the same state. That&#8217;s exactly when a view model earns its place.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Example 2: The About View</h2>



<p class="wp-block-paragraph">The second example is an About screen. It shows the app name, the version number, and a short &#8220;About us&#8221; text. These are plain strings that I just need to display.</p>


<div class="gb-container gb-container-18d4519a">

<figure class="gb-block-image gb-block-image-31c2b68e"><img loading="lazy" decoding="async" width="581" height="1143" class="gb-image gb-image-31c2b68e" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-2.webp" alt="ios app with about screen showing simple strings. implementated with a simple swiftui view without a view model" title="when-to-use-viewmodel-example-2" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-2.webp 581w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-2-152x300.webp 152w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-2-521x1024.webp 521w" sizes="auto, (max-width: 581px) 100vw, 581px" /></figure>

</div>


<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct AboutView: View {
    let appName = "Markdown Notes"
    let version = "1.2.0"
    let aboutText = "Made with love by a small team."

    var body: some View {
        VStack(spacing: 8) {
            Text(appName).font(.title)
            Text("Version (version)").foregroundStyle(.secondary)
            Text(aboutText)
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">AboutView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> appName </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Markdown Notes</span><span style="color: #DEE492">&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> version </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">1.2.0</span><span style="color: #DEE492">&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> aboutText </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Made with love by a small team.</span><span style="color: #DEE492">&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">VStack</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">spacing</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">8</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(appName).</span><span style="color: #97E1F1">font</span><span style="color: #F6F6F4">(.title)</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Version (version)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">).</span><span style="color: #97E1F1">foregroundStyle</span><span style="color: #F6F6F4">(.secondary)</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(aboutText)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Do I need a view model for this? There&#8217;s no logic and nothing to do. I could keep these values as properties, like above, or write them straight into the view body. Both are simple enough.</p>



<p class="wp-block-paragraph">If I introduced a view model, I&#8217;d be moving these strings into a separate layer and adding abstraction for no reason. And it actively hurts you. One of the drawbacks of too much abstraction is that you have to jump around in your code. If I want to know what a label shows, I have to go to another type, look it up there, and come back.</p>



<p class="wp-block-paragraph">There&#8217;s also nothing to manage. These are constants. Nothing mutates during runtime, so there&#8217;s no reason for a class, and certainly no reason for <code>@Observable</code>.</p>



<p class="wp-block-paragraph"><strong>Takeaway:</strong> if nothing changes, there&#8217;s nothing for a view model to manage.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Example 3: A Custom Button Component</h2>



<p class="wp-block-paragraph">The third example is a reusable button. Teams often want preset configurations for buttons: a trash can icon paired with red, a certain padding, a certain style.</p>


<div class="gb-container gb-container-f9480854">

<figure class="gb-block-image gb-block-image-af319e8a"><img loading="lazy" decoding="async" width="540" height="1050" class="gb-image gb-image-af319e8a" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-3.webp" alt="ios app with differnt button configurations" title="when-to-use-viewmodel-example-3" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-3.webp 540w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-3-154x300.webp 154w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-3-527x1024.webp 527w" sizes="auto, (max-width: 540px) 100vw, 540px" /></figure>

</div>


<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">The View Model Version</h3>



<p class="wp-block-paragraph">What happens if you use a view model for this configuration? Every button creates and owns its own view model, with properties for the title, color, icon, and action:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@Observable
class CustomButtonViewModel {
    var title: String
    var color: Color
    var icon: String
    var action: () -> Void
    // ...
}

CustomButton(viewModel: CustomButtonViewModel(
    title: "Delete", color: .red, icon: "trash", action: deleteItem
))</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">CustomButtonViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> title: </span><span style="color: #97E1F1; font-style: italic">String</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> color: Color</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> icon: </span><span style="color: #97E1F1; font-style: italic">String</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> action: () </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Void</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// ...</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #97E1F1">CustomButton</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">viewModel</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">CustomButtonViewModel</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">title</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Delete</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">color</span><span style="color: #F6F6F4">: .red, </span><span style="color: #97E1F1">icon</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">trash</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">action</span><span style="color: #F6F6F4">: deleteItem</span></span>
<span class="line"><span style="color: #F6F6F4">))</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">This is overkill. There&#8217;s no state that changes over time and no logic to manage. I&#8217;m just adding another layer with more code.</p>



<p class="wp-block-paragraph">And it gets worse:</p>



<ul class="wp-block-list">
<li><strong>More work for SwiftUI:</strong> every button now has an extra object that has to be allocated and tracked.</li>



<li><strong>A second source of truth:</strong> the button owns its view model, so if you pass a new configuration for the same button, it won&#8217;t update.</li>



<li><strong>More verbose usage:</strong> creating a view model just to show a button is a lot of ceremony.</li>
</ul>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">The View-Only Version</h3>



<p class="wp-block-paragraph">Compare that to the simple version, where the button just has normal properties:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>CustomButton(title: "Delete", color: .red, icon: "trash", action: deleteItem)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #97E1F1">CustomButton</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">title</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Delete</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">color</span><span style="color: #F6F6F4">: .red, </span><span style="color: #97E1F1">icon</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">trash</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">action</span><span style="color: #F6F6F4">: deleteItem)</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">This is the simplest, most SwiftUI-like version, and it does pretty much everything you need.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">For Design Systems: A Styling Struct</h3>



<p class="wp-block-paragraph">Now, what if you really want the same button with different preset stylings? Maybe you&#8217;re working with a strict design system that you built together with a UI designer. One clean way to handle this is a struct that bundles the styling properties together:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ButtonStyling {
    let foregroundColor: Color
    let backgroundColor: Color
    let icon: String?
    let font: Font

    init(foregroundColor: Color, backgroundColor: Color,
         icon: String? = nil, font: Font = .body) {
        self.foregroundColor = foregroundColor
        self.backgroundColor = backgroundColor
        self.icon = icon
        self.font = font
    }

    // presets
    static let primary = ButtonStyling(foregroundColor: .white, backgroundColor: .blue)
    static let destructive = ButtonStyling(foregroundColor: .white, backgroundColor: .red, icon: "trash")
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ButtonStyling</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> foregroundColor: Color</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> backgroundColor: Color</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> icon: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F286C4">?</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> font: Font</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">foregroundColor</span><span style="color: #F6F6F4">: Color, </span><span style="color: #62E884; font-style: italic">backgroundColor</span><span style="color: #F6F6F4">: Color,</span></span>
<span class="line"><span style="color: #F6F6F4">         </span><span style="color: #62E884; font-style: italic">icon</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">nil</span><span style="color: #F6F6F4">, </span><span style="color: #62E884; font-style: italic">font</span><span style="color: #F6F6F4">: Font </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .body) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.foregroundColor </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> foregroundColor</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.backgroundColor </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> backgroundColor</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.icon </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> icon</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.font </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> font</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// presets</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">static</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> primary </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ButtonStyling</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">foregroundColor</span><span style="color: #F6F6F4">: .white, </span><span style="color: #97E1F1">backgroundColor</span><span style="color: #F6F6F4">: .blue)</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">static</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> destructive </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ButtonStyling</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">foregroundColor</span><span style="color: #F6F6F4">: .white, </span><span style="color: #97E1F1">backgroundColor</span><span style="color: #F6F6F4">: .red, </span><span style="color: #97E1F1">icon</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">trash</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">These are all constants, because you pass them in once. The initializer gives you sensible defaults, and static presets cover the common cases. Using it stays just as easy:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>CustomButton(title: "Continue", style: .primary) { next() }
CustomButton(title: "Delete", style: .destructive) { deleteItem() }</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #97E1F1">CustomButton</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">title</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Continue</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">style</span><span style="color: #F6F6F4">: .primary) { </span><span style="color: #97E1F1">next</span><span style="color: #F6F6F4">() }</span></span>
<span class="line"><span style="color: #97E1F1">CustomButton</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">title</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Delete</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">style</span><span style="color: #F6F6F4">: .destructive) { </span><span style="color: #97E1F1">deleteItem</span><span style="color: #F6F6F4">() }</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The overhead is small. Instead of passing every property individually, you bundle them into a plain struct.</p>



<p class="wp-block-paragraph"><strong>Takeaway:</strong> configuration is not state (that changes during runtime). Reach for plain properties or a struct, not an observable.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Example 4: From Login to Account Creation</h2>



<h3 class="wp-block-heading">The Simple Version</h3>



<p class="wp-block-paragraph">For the last example, let&#8217;s say we start with a basic login view: two state properties, two text fields, and a login button. There&#8217;s no real logic yet, and the view is very simple. No view model needed. I can keep working on it since it&#8217;s still in the early stages of development.</p>


<div class="gb-container gb-container-8f624582">
<div class="gb-container gb-container-b5d7b9a2">

<figure class="gb-block-image gb-block-image-550bad59"><img loading="lazy" decoding="async" width="540" height="998" class="gb-image gb-image-550bad59" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-4.webp" alt="ios app with simple login view in SwiftUI" title="when-to-use-viewmodel-example-4" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-4.webp 540w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-4-162x300.webp 162w" sizes="auto, (max-width: 540px) 100vw, 540px" /></figure>

</div>
</div>


<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct LoginView: View {
    @State private var email = ""
    @State private var password = ""

    var body: some View {
        VStack {
            TextField("Email", text: $email)
            SecureField("Password", text: $password)
            Button("Login") {
                if !email.isEmpty &amp;&amp; !password.isEmpty {
                    print("Try login...")
                }
            }
        }
        .padding()
        .textFieldStyle(.roundedBorder)
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">LoginView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> email </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> password </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">VStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">TextField</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Email</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">text</span><span style="color: #F6F6F4">: $email)</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">SecureField</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Password</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">text</span><span style="color: #F6F6F4">: $password)</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Button</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Login</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">!</span><span style="color: #F6F6F4">email.</span><span style="color: #BF9EEE">isEmpty</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">&amp;&amp;</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">!</span><span style="color: #F6F6F4">password.</span><span style="color: #BF9EEE">isEmpty</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Try login...</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">                }</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">padding</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">textFieldStyle</span><span style="color: #F6F6F4">(.roundedBorder)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">When the Requirements Change</h3>



<p class="wp-block-paragraph">At some point, you have to add a <strong>Create Account</strong> feature. Now you need:</p>



<ul class="wp-block-list">
<li><strong>Live validation</strong>, showing error messages while the user types their email</li>



<li><strong>Password strength feedback</strong>, with a red, yellow, or green indicator</li>



<li><strong>Loading states</strong>, because pressing <strong>Create Account</strong> sends an API request. While it&#8217;s running, the button has to be disabled so the user can&#8217;t create the same account twice. Otherwise the first request succeeds and the second fails with &#8220;email already taken.&#8221;</li>



<li><strong>Proper error handling</strong>, so the user always knows what&#8217;s going on</li>
</ul>



<p class="wp-block-paragraph">That&#8217;s a lot more logic than the simple login view. Especially once network requests are involved, a small view easily grows and grows until it becomes unmanageable.</p>


<div class="gb-container gb-container-e5bef27d">

<figure class="gb-block-image gb-block-image-0f3ca2ea"><img loading="lazy" decoding="async" width="1014" height="989" class="gb-image gb-image-0f3ca2ea" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-5.webp" alt="ios app with create account view using a view model in SwiftUI" title="when-to-use-viewmodel-example-5" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-5.webp 1014w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-5-300x293.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/10/when-to-use-viewmodel-example-5-768x749.webp 768w" sizes="auto, (max-width: 1014px) 100vw, 1014px" /></figure>

</div>


<p class="wp-block-paragraph">This is where a view model becomes a state engine. It manages all the state and the mutations, so the view can stay simple:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@MainActor
@Observable
final class AuthViewModel {
    var email = ""
    var password = ""
    private(set) var isLoading = false
    private(set) var errorMessage: String?
    private(set) var isLoggedIn = false

    private let authService: AuthService

    init(authService: AuthService = AuthService()) {
        self.authService = authService
    }

    var emailError: String? { /* live email validation */ }
    var passwordStrength: PasswordStrength { /* weak, medium, strong */ }

    var canSubmit: Bool {
        emailError == nil &amp;&amp; passwordStrength != .weak &amp;&amp; !isLoading
    }

    func createAccount() async {
        await perform { try await self.authService.createAccount(email: self.email, password: self.password) }
    }

    func login() async {
        await perform { try await self.authService.login(email: self.email, password: self.password) }
    }

    // One place that runs every auth request the same way
    private func perform(_ request: () async throws -> Void) async {
        isLoading = true
        errorMessage = nil
        defer { isLoading = false }
        do {
            try await request()
            isLoggedIn = true
        } catch {
            errorMessage = error.localizedDescription
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">AuthViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> email </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> password </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> isLoading </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">false</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> errorMessage: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F286C4">?</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> isLoggedIn </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">false</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> authService: AuthService</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">authService</span><span style="color: #F6F6F4">: AuthService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">AuthService</span><span style="color: #F6F6F4">()) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.authService </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> authService</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> emailError: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> { </span><span style="color: #7B7F8B">/* live email validation */</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> passwordStrength: PasswordStrength { </span><span style="color: #7B7F8B">/* weak, medium, strong */</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> canSubmit: </span><span style="color: #97E1F1; font-style: italic">Bool</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        emailError </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">nil</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">&amp;&amp;</span><span style="color: #F6F6F4"> passwordStrength </span><span style="color: #F286C4">!=</span><span style="color: #F6F6F4"> .weak </span><span style="color: #F286C4">&amp;&amp;</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">!</span><span style="color: #F6F6F4">isLoading</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">createAccount</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">perform</span><span style="color: #F6F6F4"> { </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.authService.</span><span style="color: #97E1F1">createAccount</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">email</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.email, </span><span style="color: #97E1F1">password</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.password) }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">login</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">perform</span><span style="color: #F6F6F4"> { </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.authService.</span><span style="color: #97E1F1">login</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">email</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.email, </span><span style="color: #97E1F1">password</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.password) }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// One place that runs every auth request the same way</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">perform</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">request</span><span style="color: #F6F6F4">: () </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">throws</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Void</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        isLoading </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">true</span></span>
<span class="line"><span style="color: #F6F6F4">        errorMessage </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">nil</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">defer</span><span style="color: #F6F6F4"> { isLoading </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">false</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">do</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">request</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">            isLoggedIn </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">true</span></span>
<span class="line"><span style="color: #F6F6F4">        } </span><span style="color: #F286C4">catch</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            errorMessage </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> error.localizedDescription</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">This is a shortened version. In a real app, the validation alone adds up to a lot more code. But even with all of that, the view stays small. It manages its text fields, builds the button, and calls the view model. Disabling the button is one line using <code>canSubmit</code>.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Sharing State Mutations Across Views</h3>



<p class="wp-block-paragraph">There&#8217;s another big advantage once this logic lives in a view model: <strong>it&#8217;s no longer tied to a single view</strong>.</p>



<p class="wp-block-paragraph">The create account screen isn&#8217;t the only place that deals with authentication. I also have a login screen, and maybe a sign-in prompt somewhere else in the app with a completely different look. All of these views work with the same auth state: whether a request is loading, whether there&#8217;s an error, whether the user is logged in. And login state is usually something you need app-wide anyway.</p>



<p class="wp-block-paragraph">Instead of writing that logic again in every view, I can simply pass the view model along and call its methods:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct LoginView: View {
    @Bindable var auth: AuthViewModel

    var body: some View {
        VStack {
            TextField("Email", text: $auth.email)
            SecureField("Password", text: $auth.password)

            Button("Log In") {
                Task { await auth.login() }
            }
            .disabled(!auth.canSubmit)

            if let error = auth.errorMessage {
                Text(error).foregroundStyle(.red)
            }
        }
    }
}

struct CreateAccountView: View {
    @Bindable var auth: AuthViewModel

    var body: some View {
        // Different layout, same view model
        Button("Create Account") {
            Task { await auth.createAccount() }
        }
        .disabled(!auth.canSubmit)
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">LoginView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Bindable</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> auth: AuthViewModel</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">VStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">TextField</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Email</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">text</span><span style="color: #F6F6F4">: $auth.email)</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">SecureField</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Password</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">text</span><span style="color: #F6F6F4">: $auth.password)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Button</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Log In</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">Task</span><span style="color: #F6F6F4"> { </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> auth.</span><span style="color: #97E1F1">login</span><span style="color: #F6F6F4">() }</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">disabled</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">!</span><span style="color: #F6F6F4">auth.canSubmit)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> error </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> auth.errorMessage {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(error).</span><span style="color: #97E1F1">foregroundStyle</span><span style="color: #F6F6F4">(.red)</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">CreateAccountView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Bindable</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> auth: AuthViewModel</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #7B7F8B">// Different layout, same view model</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Button</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Create Account</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Task</span><span style="color: #F6F6F4"> { </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> auth.</span><span style="color: #97E1F1">createAccount</span><span style="color: #F6F6F4">() }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">disabled</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">!</span><span style="color: #F6F6F4">auth.canSubmit)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Both views look different, but neither of them knows how logging in or creating an account works. They call <code>login()</code> or <code>createAccount()</code>, and the view model takes care of the rest.</p>



<p class="wp-block-paragraph">This matters because these are complex state mutations. Setting the loading state, clearing old errors, handling a failed request, and updating the logged-in state all have to happen in the right order. If every view did this on its own, I&#8217;d end up duplicating very similar code that mutates the same state, and sooner or later one copy would behave slightly differently from the others. <strong>With the view model, there&#8217;s one place responsible for how the auth state changes, and every view shares those same methods</strong>.</p>



<p class="wp-block-paragraph">This is also why the view model isn&#8217;t owned by any one of these screens. It&#8217;s owned higher up, where all of them can reach it. I explain this approach in more detail in <a href="https://www.swiftyplace.com/blog/swiftui-mvvm" data-type="post" data-id="1005742">What Is a View Model in SwiftUI, Really?</a>, under &#8220;scope by state, not by screen.&#8221;</p>



<p class="wp-block-paragraph"><strong>Takeaway:</strong> complex state mutations and state shared across views are exactly what view models are for.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">The Pattern Behind the Examples</h2>



<p class="wp-block-paragraph">If you look at the four examples side by side, a pattern shows up. Whenever there was real state to manage and real mutations to get right, the view model paid off. Whenever there wasn&#8217;t, it only added cost.</p>



<p class="wp-block-paragraph"><strong>A view model is usually worth it when:</strong></p>



<ul class="wp-block-list">
<li>The view needs real logic: validation, persistence, networking</li>



<li>State changes over time, and those changes need to be coordinated</li>



<li>Several views work with the same state and should share the methods that change it</li>



<li>The state needs to outlive the view that displays it</li>
</ul>



<p class="wp-block-paragraph"><strong>It&#8217;s usually overkill when:</strong></p>



<ul class="wp-block-list">
<li>The view only displays constants or simple values</li>



<li>You&#8217;re configuring a reusable component</li>



<li>The view model would hold little more than the properties the view already has</li>
</ul>



<p class="wp-block-paragraph">Notice that none of these points is about the size of the screen or how important it feels. It all comes back to the definition: a view model owns UI state and is responsible for mutating it properly. If there&#8217;s no state to own and no mutations to get right, there&#8217;s no job for a view model to do.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Start Simple, Refactor When It Grows</h2>



<p class="wp-block-paragraph">You might have noticed that two of the examples started without a view model and only needed one later. That&#8217;s very typical. Most view models aren&#8217;t planned up front. They show up when a view starts collecting logic.</p>



<p class="wp-block-paragraph">So you don&#8217;t need to decide on day one. Start with the simplest version that works, and keep an eye out for these signs:</p>



<ul class="wp-block-list">
<li>The view body gets long, and most of it isn&#8217;t UI</li>



<li>State mutations are scattered across subviews, or duplicated in slightly different versions</li>



<li>It&#8217;s getting hard to follow how and when the state changes</li>



<li>A second view suddenly needs the same state</li>
</ul>



<p class="wp-block-paragraph">When you see them, that&#8217;s the moment to move the state and its mutations into a view model. I&#8217;ll walk through that refactoring step by step in Refactoring to a View Model When Complexity Grows.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Wrapping Up</h2>



<p class="wp-block-paragraph">There&#8217;s no solution that fits all. Whether you use a view model in a given situation is really up to you, and it comes down to one question: is this extra layer worth it here?</p>



<p class="wp-block-paragraph">You don&#8217;t have to use one. A view-only solution is often the simplest and best choice. But when your views start collecting state and mutations that need to happen consistently, a view model is a very good tool for managing that complexity.</p>



<p class="wp-block-paragraph">Once you&#8217;ve decided you need one, the next question is what actually belongs inside it. That&#8217;s what we&#8217;ll look at in What Should Go in a View Model?</p>


<div class="gb-container gb-container-c5dedc2e">
<div class="gb-container gb-container-f7a433c7">
<div class="gb-container gb-container-7a8dc7a3">

<figure class="gb-block-image gb-block-image-f04fbbad"><a href="https://www.swiftyplace.com/free-swiftui-layout-cookbook" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" width="1446" height="1552" class="gb-image gb-image-f04fbbad" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm.webp" alt="" title="lead magnet mvvm" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm.webp 1446w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-280x300.webp 280w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-954x1024.webp 954w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-768x824.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-1431x1536.webp 1431w" sizes="auto, (max-width: 1446px) 100vw, 1446px" /></a></figure>

</div>

<div class="gb-container gb-container-98352fe6">

<h4 class="gb-headline gb-headline-4aacd94c gb-headline-text">Get the MVVM SwiftUI Cheat Sheet</h4>



<p class="gb-headline gb-headline-5e6c4f85 gb-headline-text">The cheat sheet puts the whole system on a few pages: what goes in a view model, which view owns it, how to pass it down the tree, common mistakes, and code skeletons you can copy.</p>


<div class="gb-container gb-container-34a8ad02">

<a class="gb-button gb-button-63e90e76 gb-button-blue" href="https://school.swiftyplace.com/f/swiftui-mvvm-cheat-sheet" target="_blank" rel="noopener noreferrer"><span class="gb-button-text">Get the free cheat sheet</span><span class="gb-icon"><svg aria-hidden="true" role="img" height="1em" width="1em" viewBox="0 0 256 512" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M224.3 273l-136 136c-9.4 9.4-24.6 9.4-33.9 0l-22.6-22.6c-9.4-9.4-9.4-24.6 0-33.9l96.4-96.4-96.4-96.4c-9.4-9.4-9.4-24.6 0-33.9L54.3 103c9.4-9.4 24.6-9.4 33.9 0l136 136c9.5 9.4 9.5 24.6.1 34z"></path></svg></span></a>

</div>
</div>
</div>
</div><p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/mvvm-view-model-use-case">When to Use a View Model in SwiftUI (and When It&#8217;s Overkill)</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.swiftyplace.com/blog/mvvm-view-model-use-case/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>What Is a View Model in SwiftUI MVVM, Really</title>
		<link>https://www.swiftyplace.com/blog/swiftui-mvvm?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=swiftui-mvvm</link>
					<comments>https://www.swiftyplace.com/blog/swiftui-mvvm#respond</comments>
		
		<dc:creator><![CDATA[Karin Prater]]></dc:creator>
		<pubDate>Fri, 16 Oct 2026 11:02:43 +0000</pubDate>
				<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[SwiftUI Architecture]]></category>
		<guid isPermaLink="false">https://www.swiftyplace.com/?p=1005742</guid>

					<description><![CDATA[<p>Learn how to apply MVVM in SwiftUI. Find out what a view model actually is, what it’s responsible for, and how it fits between your views and your data. A clear, practical introduction with real SwiftUI code examples to help you keep your views simple and your app state under control.</p>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/swiftui-mvvm">What Is a View Model in SwiftUI MVVM, Really</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">If you&#8217;ve spent any time reading about SwiftUI architecture, you&#8217;ve probably run into the term &#8220;view model.&#8221; And you&#8217;ve probably noticed that it means different things to different people. Some tutorials add a view model to every single view without ever explaining why. Others say SwiftUI doesn&#8217;t need view models at all, because &#8220;the view is already the view model.&#8221;</p>



<p class="wp-block-paragraph">So what is a view model, really? In this post, I want to give you a clear, practical definition that you can apply to your own code. Here&#8217;s the main rule that I find most practical, so you have something to hold on to:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>A view model owns UI state and is responsible for mutating that state properly and consistently.</strong></p>
</blockquote>



<p class="wp-block-paragraph">Notice what&#8217;s not in that sentence: a single view. A view model isn&#8217;t tied to one view. It can support one view, an entire screen, or several views that share the same state. (Other people might say otherwise, but I am giving you the system that works best for me)</p>



<p class="wp-block-paragraph">That responsibility is the whole point. In SwiftUI, state drives the UI. When something on screen is wrong, the cause is almost always state that&#8217;s wrong. And state goes wrong because the code that mutates it is messy: scattered across views, duplicated in slightly different versions, or running steps in the wrong order. A view model gives those mutations one home, so they happen the same way every time.</p>



<p class="wp-block-paragraph">That&#8217;s it. Everything else in this post explains what that means, why it&#8217;s useful, and where the boundaries are.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Where MVVM Comes From</h2>



<p class="wp-block-paragraph">MVVM stands for <a href="https://en.wikipedia.org/wiki/Model–view–viewmodel" data-type="link" data-id="https://en.wikipedia.org/wiki/Model–view–viewmodel" target="_blank" rel="noopener">Model-View-ViewModel.</a> It was introduced in 2005 by Microsoft architects Ken Cooper and Ted Peters. I don&#8217;t usually spend much time on history, but here it matters because understanding where the pattern came from helps us understand what it&#8217;s actually trying to do.</p>



<p class="wp-block-paragraph">MVVM was born in Windows Presentation Foundation, or WPF. The UI in WPF is written in XAML, a declarative markup language, and it relies heavily on data bindings and reactive updates. In other words, it&#8217;s state-driven, declarative programming. Sound familiar? That&#8217;s very close to how SwiftUI works.</p>



<p class="wp-block-paragraph">So what problem was MVVM designed to solve? It came down to people. In WPF, teams naturally split into two groups: UI-facing developers, who Microsoft called &#8220;designer developers,&#8221; and logic developers working behind the scenes. The challenge was letting these two groups work in parallel without stepping on each other&#8217;s toes.</p>



<p class="wp-block-paragraph">What kept happening was that logic crept into the view: network requests, formatting, data transformations. The view code became cluttered and hard to maintain, and when everyone has to work in the same file, collaboration breaks down fast.</p>



<p class="wp-block-paragraph">The solution was to pull that complex logic out of the view and into a separate layer. The view was left with nothing but declarative UI, and the logic developers had their own layer to work in. That separate layer is the view model.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">The Backing Layer: A Presentation Layer Pattern</h2>



<p class="wp-block-paragraph">The best way to think about a view model is as the backing layer behind your UI. You have the view on one side and your data on the other, and you place an intermediate layer in between. That layer handles the more complex concerns: state management, formatting, anything you don&#8217;t want cluttering your view code.</p>



<p class="wp-block-paragraph">I like to compare it to an old-school calculator. On the front, you see the buttons and the display. That&#8217;s your view. Now imagine you unscrew the case and look inside: the battery, the circuit board, some cables. That&#8217;s your backing layer. As a user, you just want to press buttons and get results. You don&#8217;t want to see or deal with the internals. A view model works the same way: it keeps the inner workings hidden behind a clean surface.</p>



<figure class="gb-block-image gb-block-image-7f65d7e5"><img loading="lazy" decoding="async" width="978" height="314" class="gb-image gb-image-7f65d7e5" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-layers-calculator.webp" alt="" title="mvvm-layers-calculator" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-layers-calculator.webp 978w, https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-layers-calculator-300x96.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-layers-calculator-768x247.webp 768w" sizes="auto, (max-width: 978px) 100vw, 978px" /></figure>



<div style="height:16px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">That&#8217;s why I often prefer the term <strong>UI backing layer</strong> over &#8220;view model.&#8221; It describes what the thing actually does.</p>



<p class="wp-block-paragraph">This also leads to an important clarification. Because we&#8217;re talking about layers, you&#8217;ll sometimes hear MVVM described as a &#8220;UI architecture pattern.&#8221; That can be misleading, because it gives the impression that MVVM is a full app architecture. It&#8217;s not. <strong>MVVM is a presentation layer pattern.</strong> It&#8217;s about the view and the code that directly backs it.</p>



<ul class="wp-block-list">
<li>It&#8217;s not about visual design, like layout, colors, or components.</li>



<li>It doesn&#8217;t tell you how to structure your whole app. Networking, persistence, navigation, and dependencies need their own layers and patterns.</li>



<li>At its core, it&#8217;s about separation of concerns within the UI layer.</li>
</ul>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">The Three Layers</h2>



<p class="wp-block-paragraph">Let&#8217;s look at each part of the pattern and what it&#8217;s responsible for.</p>


<div class="gb-container gb-container-187b7444">

<figure class="gb-block-image gb-block-image-c09039d3"><img loading="lazy" decoding="async" width="966" height="674" class="gb-image gb-image-c09039d3" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-layers-flow.webp" alt="representation layer in SwiftUI apps with MVVM" title="mvvm-layers-flow" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-layers-flow.webp 966w, https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-layers-flow-300x209.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/10/mvvm-layers-flow-768x536.webp 768w" sizes="auto, (max-width: 966px) 100vw, 966px" /></figure>

</div>


<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">The View</h3>



<p class="wp-block-paragraph">The view is the UI layer. In SwiftUI, these are your <code>View</code> structs, and their job is to <strong>take state and decide what to display.</strong> Logged in? Show the main content. Logged out? Show the login screen.</p>



<p class="wp-block-paragraph">Views also handle the finer details of presentation. Is a button enabled or disabled? What text goes into a label? What font, what position, what layout? These are all view concerns. The view is the part that makes things look good.</p>



<p class="wp-block-paragraph">Views also receive user interactions. When someone taps a button, the view picks that up. Sometimes it handles the interaction directly, but more often it passes the user&#8217;s intent along to the view model. The view just says &#8220;the user tapped this&#8221; and moves on.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">The View Model</h3>



<p class="wp-block-paragraph">The view model is the UI backing layer. Because SwiftUI is state-driven, everything revolves around UI state, and managing that state can get complex. When do you change it? What moves you from loading to success, or to an error? What happens when a network request comes back? All of this needs to live somewhere, and that somewhere is the view model.</p>



<p class="wp-block-paragraph">The view model owns the UI state and decides when and how it changes. It can also prepare data for display, like formatting a price, and act as a gatekeeper for what&#8217;s allowed to happen.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">The Model</h3>



<p class="wp-block-paragraph">The model is your data: the structures your app works with, and the logic that naturally belongs to that data, like validation rules.</p>



<p class="wp-block-paragraph">You&#8217;ll find that different developers mean different things by &#8220;model.&#8221; Some put their networking code here too. That&#8217;s a valid interpretation, but to keep things clear, I keep the model narrow: the data itself, plus the logic intrinsic to it.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">What Defines a View Model: UI State + Mutations</h2>



<p class="wp-block-paragraph">You can characterize any view model by two things: what state it holds, and how it can change that state. That&#8217;s really all that defines it.</p>



<ul class="wp-block-list">
<li><strong>UI state:</strong> the data your views need to render. The items in a list, whether something is loading, an error message, which item is selected, whether a button is allowed to be tapped.</li>



<li><strong>Methods to change UI state:</strong> controlled mutations of that data. Adding an item, logging in, deleting a theme.</li>
</ul>



<p class="wp-block-paragraph">Because the view model backs the UI, its state has to be connected to the views that display it. That comes with two technical requirements:</p>



<ul class="wp-block-list">
<li><strong><code>@Observable</code></strong>: SwiftUI needs to track the state so it can update the views whenever it changes. Without observation, the view has no way of knowing that something happened.</li>



<li><strong><code>@MainActor</code></strong>: the UI reads this state, and UI work happens on the main actor. So the state, and the code that changes it, lives there too.</li>
</ul>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@MainActor
@Observable
final class CartViewModel {
    private(set) var items: &#91;CartItem&#93; = []   // UI state

    func addItem(id: String) { /* ... */ }    // mutation
    func removeItem(id: String) { /* ... */ } // mutation
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">CartViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> items: &#91;CartItem&#93; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []   </span><span style="color: #7B7F8B">// UI state</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">addItem</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">id</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">) { </span><span style="color: #7B7F8B">/* ... */</span><span style="color: #F6F6F4"> }    </span><span style="color: #7B7F8B">// mutation</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">removeItem</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">id</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">) { </span><span style="color: #7B7F8B">/* ... */</span><span style="color: #F6F6F4"> } </span><span style="color: #7B7F8B">// mutation</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">There&#8217;s one more rule I find really helpful: <strong>a view model communicates through state, never through UI instructions.</strong> Say a user isn&#8217;t allowed to buy a certain product. The view model doesn&#8217;t say &#8220;disable the button.&#8221; It says &#8220;this action is not allowed.&#8221; The view is the one that translates that into a disabled button.</p>



<p class="wp-block-paragraph">In the same way, a view model can prepare data for display, like turning a raw price into a formatted string. But it never decides how that information is rendered. It knows <em>what</em> to show, never <em>how</em> to show it. That&#8217;s view territory.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Why Put State and Mutations Together?</h2>



<p class="wp-block-paragraph">I like to use the law of proximity here: <strong>things that change together should live together.</strong></p>



<p class="wp-block-paragraph">You can look at UI state from two directions. When the state changes, the UI changes, so the state should live close to the views that use it. That&#8217;s true. But the state and the code that <em>changes</em> it belong together just as tightly.</p>



<p class="wp-block-paragraph">Think about a SwiftUI view hierarchy where several views use the same state, and each of those subviews can mutate it. The state declaration moves higher up the view tree, but the code that changes it is scattered across different subviews. Things get messy quickly. If you want to know where a value was changed, you have to go hunting through the hierarchy.</p>



<p class="wp-block-paragraph">A view model brings them back together. The state lives in one place, and the methods that change it live right next to it. You get a single source of truth for the state, and one place that&#8217;s responsible for changing it properly and consistently.</p>



<p class="wp-block-paragraph">That gives you a few concrete benefits:</p>



<ul class="wp-block-list">
<li><strong>Consistent mutations:</strong> every change goes through the same methods, so it happens the same way every time.</li>



<li><strong>No duplicated logic:</strong> if several views need to make the same change, they call the same method. Duplicated logic tends to drift. Sooner or later you update one copy and forget the other, and your state goes out of sync.</li>



<li><strong>Easier to follow:</strong> when you want to know how the state changes, you look in one place.</li>
</ul>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>


<div class="gb-container gb-container-c5dedc2e">
<div class="gb-container gb-container-f7a433c7">
<div class="gb-container gb-container-7a8dc7a3">

<figure class="gb-block-image gb-block-image-f04fbbad"><a href="https://www.swiftyplace.com/free-swiftui-layout-cookbook" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" width="1446" height="1552" class="gb-image gb-image-f04fbbad" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm.webp" alt="" title="lead magnet mvvm" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm.webp 1446w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-280x300.webp 280w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-954x1024.webp 954w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-768x824.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-1431x1536.webp 1431w" sizes="auto, (max-width: 1446px) 100vw, 1446px" /></a></figure>

</div>

<div class="gb-container gb-container-98352fe6">

<h4 class="gb-headline gb-headline-4aacd94c gb-headline-text">Get the MVVM SwiftUI Cheat Sheet</h4>



<p class="gb-headline gb-headline-5e6c4f85 gb-headline-text">The cheat sheet puts the whole system on a few pages: what goes in a view model, which view owns it, how to pass it down the tree, common mistakes, and code skeletons you can copy.</p>


<div class="gb-container gb-container-34a8ad02">

<a class="gb-button gb-button-63e90e76 gb-button-blue" href="https://school.swiftyplace.com/f/swiftui-mvvm-cheat-sheet" target="_blank" rel="noopener noreferrer"><span class="gb-button-text">Get the free cheat sheet</span><span class="gb-icon"><svg aria-hidden="true" role="img" height="1em" width="1em" viewBox="0 0 256 512" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M224.3 273l-136 136c-9.4 9.4-24.6 9.4-33.9 0l-22.6-22.6c-9.4-9.4-9.4-24.6 0-33.9l96.4-96.4-96.4-96.4c-9.4-9.4-9.4-24.6 0-33.9L54.3 103c9.4-9.4 24.6-9.4 33.9 0l136 136c9.5 9.4 9.5 24.6.1 34z"></path></svg></span></a>

</div>
</div>
</div>
</div>


<div style="height:46px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Example: The Shopping Cart</h2>



<p class="wp-block-paragraph">Let&#8217;s see how these layers play out with a shopping cart.</p>



<p class="wp-block-paragraph"></p>


<div class="gb-container gb-container-08f18f86">

<figure class="gb-block-image gb-block-image-ad983c4f"><img loading="lazy" decoding="async" width="1158" height="1152" class="gb-image gb-image-ad983c4f" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/Preseentation-Layer-Backing-example.jpg" alt="" title="Preseentation Layer - Backing - example" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/Preseentation-Layer-Backing-example.jpg 1158w, https://www.swiftyplace.com/wp-content/uploads/2026/10/Preseentation-Layer-Backing-example-300x298.jpg 300w, https://www.swiftyplace.com/wp-content/uploads/2026/10/Preseentation-Layer-Backing-example-1024x1019.jpg 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/10/Preseentation-Layer-Backing-example-150x150.jpg 150w, https://www.swiftyplace.com/wp-content/uploads/2026/10/Preseentation-Layer-Backing-example-768x764.jpg 768w" sizes="auto, (max-width: 1158px) 100vw, 1158px" /></figure>

</div>


<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">The Model</h3>



<p class="wp-block-paragraph">The model is the raw data: a cart item with a product ID and a quantity, and the product information itself.</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct CartItem {
    let id: String
    var quantity: Int
}

struct Product {
    let id: String
    let name: String
    let price: Double
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">CartItem</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> id: </span><span style="color: #97E1F1; font-style: italic">String</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> quantity: </span><span style="color: #97E1F1; font-style: italic">Int</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Product</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> id: </span><span style="color: #97E1F1; font-style: italic">String</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> name: </span><span style="color: #97E1F1; font-style: italic">String</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> price: </span><span style="color: #97E1F1; font-style: italic">Double</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">This isn&#8217;t what the UI wants to show, though. The view needs a name, a quantity, and nicely formatted prices, all in one place. So we add a display type that has exactly what the view needs:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct CartDisplayItem {
    let id: String
    let name: String
    let quantity: Int
    let formattedPrice: String
    let formattedSubtotal: String
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">CartDisplayItem</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> id: </span><span style="color: #97E1F1; font-style: italic">String</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> name: </span><span style="color: #97E1F1; font-style: italic">String</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> quantity: </span><span style="color: #97E1F1; font-style: italic">Int</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> formattedPrice: </span><span style="color: #97E1F1; font-style: italic">String</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> formattedSubtotal: </span><span style="color: #97E1F1; font-style: italic">String</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">The View Model</h3>



<p class="wp-block-paragraph">The view model owns the state of what&#8217;s in the cart. It turns the raw data into display items, calculates the total, and acts as a gatekeeper: if the view wants to change the cart, it has to call <code>addItem</code> or <code>removeItem</code>. It can&#8217;t reach in and change the items directly, which is what <code>private(set)</code> makes sure of.</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@MainActor
@Observable
final class CartViewModel {
    private(set) var items: &#91;CartItem&#93; = []
    private let products: &#91;String: Product&#93;

    init(products: &#91;String: Product&#93;) {
        self.products = products
    }

    // Converts model data into what the view displays
    var displayItems: &#91;CartDisplayItem&#93; {
        items.compactMap { item in
            guard let product = products&#91;item.id&#93; else { return nil }
            let subtotal = product.price * Double(item.quantity)
            return CartDisplayItem(
                id: item.id,
                name: product.name,
                quantity: item.quantity,
                formattedPrice: formatPrice(product.price),
                formattedSubtotal: formatPrice(subtotal)
            )
        }
    }

    var formattedTotal: String {
        let total = items.reduce(0.0) { sum, item in
            guard let product = products&#91;item.id&#93; else { return sum }
            return sum + product.price * Double(item.quantity)
        }
        return formatPrice(total)
    }

    // Gatekeeper: the view tells us what it wants, we decide if it's allowed
    func canAddItem(id: String) -> Bool {
        true // e.g. check stock or purchase limits
    }

    func addItem(id: String) {
        if let index = items.firstIndex(where: { $0.id == id }) {
            items&#91;index&#93;.quantity += 1
        } else {
            items.append(CartItem(id: id, quantity: 1))
        }
    }

    func removeItem(id: String) {
        items.removeAll { $0.id == id }
    }

    private func formatPrice(_ price: Double) -> String {
        price.formatted(.currency(code: "USD"))
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">CartViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> items: &#91;CartItem&#93; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> products: &#91;</span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F286C4">:</span><span style="color: #F6F6F4"> Product&#93;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">products</span><span style="color: #F6F6F4">: &#91;</span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F286C4">:</span><span style="color: #F6F6F4"> Product&#93;) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.products </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> products</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// Converts model data into what the view displays</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> displayItems: &#91;CartDisplayItem&#93; {</span></span>
<span class="line"><span style="color: #F6F6F4">        items.</span><span style="color: #97E1F1">compactMap</span><span style="color: #F6F6F4"> { item </span><span style="color: #F286C4">in</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">guard</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> product </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> products&#91;item.id&#93; </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> { </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">nil</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> subtotal </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> product.price </span><span style="color: #F286C4">*</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Double</span><span style="color: #F6F6F4">(item.quantity)</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">CartDisplayItem</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">id</span><span style="color: #F6F6F4">: item.id,</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">name</span><span style="color: #F6F6F4">: product.name,</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">quantity</span><span style="color: #F6F6F4">: item.quantity,</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">formattedPrice</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">formatPrice</span><span style="color: #F6F6F4">(product.price),</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">formattedSubtotal</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">formatPrice</span><span style="color: #F6F6F4">(subtotal)</span></span>
<span class="line"><span style="color: #F6F6F4">            )</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> formattedTotal: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> total </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> items.</span><span style="color: #97E1F1">reduce</span><span style="color: #F6F6F4">(</span><span style="color: #BF9EEE">0.0</span><span style="color: #F6F6F4">) { sum, item </span><span style="color: #F286C4">in</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">guard</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> product </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> products&#91;item.id&#93; </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> { </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> sum }</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> sum </span><span style="color: #F286C4">+</span><span style="color: #F6F6F4"> product.price </span><span style="color: #F286C4">*</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Double</span><span style="color: #F6F6F4">(item.quantity)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">formatPrice</span><span style="color: #F6F6F4">(total)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// Gatekeeper: the view tells us what it wants, we decide if it&#39;s allowed</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">canAddItem</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">id</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Bool</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE">true</span><span style="color: #F6F6F4"> </span><span style="color: #7B7F8B">// e.g. check stock or purchase limits</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">addItem</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">id</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> index </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> items.</span><span style="color: #97E1F1">firstIndex</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">where</span><span style="color: #F6F6F4">: { </span><span style="color: #BF9EEE; font-style: italic">$0</span><span style="color: #F6F6F4">.id </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> id }) {</span></span>
<span class="line"><span style="color: #F6F6F4">            items&#91;index&#93;.quantity </span><span style="color: #F286C4">+=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">1</span></span>
<span class="line"><span style="color: #F6F6F4">        } </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            items.</span><span style="color: #97E1F1">append</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">CartItem</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">id</span><span style="color: #F6F6F4">: id, </span><span style="color: #97E1F1">quantity</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">1</span><span style="color: #F6F6F4">))</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">removeItem</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">id</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">        items.</span><span style="color: #97E1F1">removeAll</span><span style="color: #F6F6F4"> { </span><span style="color: #BF9EEE; font-style: italic">$0</span><span style="color: #F6F6F4">.id </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> id }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">formatPrice</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">price</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Double</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        price.</span><span style="color: #97E1F1">formatted</span><span style="color: #F6F6F4">(.</span><span style="color: #97E1F1">currency</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">code</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">USD</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">))</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">The View</h3>



<p class="wp-block-paragraph">With all that logic in the view model, the view becomes very simple. No formatting, no calculations. Just a <code>ForEach</code> with some <code>Text</code> views, a font, and a <code>disabled</code> modifier.</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct CartView: View {
     var viewModel: CartViewModel

    var body: some View {
        VStack {
            ForEach(viewModel.displayItems, id: .id) { item in
                HStack {
                    Text(item.name)
                    Text("×(item.quantity)")
                    Spacer()
                    Text(item.formattedSubtotal)
                }
            }

            Text("Total: (viewModel.formattedTotal)")
                .font(.headline)

            Button("Add iPhone") {
                viewModel.addItem(id: "iphone")
            }
            .disabled(!viewModel.canAddItem(id: "iphone"))
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">CartView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">     </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> viewModel: CartViewModel</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">VStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">ForEach</span><span style="color: #F6F6F4">(viewModel.displayItems, </span><span style="color: #97E1F1">id</span><span style="color: #F6F6F4">: .id) { item </span><span style="color: #F286C4">in</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">HStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(item.name)</span></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">×(item.quantity)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">Spacer</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(item.formattedSubtotal)</span></span>
<span class="line"><span style="color: #F6F6F4">                }</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Total: (viewModel.formattedTotal)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">                .</span><span style="color: #97E1F1">font</span><span style="color: #F6F6F4">(.headline)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Button</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Add iPhone</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">                viewModel.</span><span style="color: #97E1F1">addItem</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">id</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">iphone</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">disabled</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">!</span><span style="color: #F6F6F4">viewModel.</span><span style="color: #97E1F1">canAddItem</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">id</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">iphone</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">))</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Notice how <code>canAddItem</code> works. The view model only answers &#8220;is this allowed?&#8221; The view decides that &#8220;not allowed&#8221; means a disabled button.</p>



<p class="wp-block-paragraph">Now imagine all of this living inside the view: the price formatting, the subtotal and total calculations, the rules for adding and removing items. The view would get big and messy fast, and every other view that touches the cart would need its own copy of that logic.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">&#8220;One View Model per Screen&#8221;: A Rule That Trips You Up</h2>



<p class="wp-block-paragraph">You&#8217;ll often hear that MVVM comes with a rule: one view model per screen, or even one per view. I understand why people like it. It&#8217;s simple, it&#8217;s easy to explain, and every screen gets its own neat little backing class.</p>



<p class="wp-block-paragraph">But I think it&#8217;s a rule that breaks your app sooner or later, because it goes directly against the single source of truth.</p>



<p class="wp-block-paragraph">Think about the shopping cart. The cart screen shows the items. But the product list also needs the cart: the user adds items from there, and maybe the tab bar shows a badge with the number of items. If every screen gets its own view model, you now have two view models holding their own copy of the cart. Add an item on the product list, and the cart screen doesn&#8217;t know about it. So you start syncing them: notifications, callbacks, reloading on appear. That&#8217;s exactly the messy state we wanted to avoid. You also end up writing the same <code>addItem</code> logic twice, and those two versions will drift apart.</p>



<p class="wp-block-paragraph">There&#8217;s a second problem: lifetime. A view model created by a screen lives only as long as that screen. Navigate away and back, and the state is gone and has to be loaded again, even if it should have survived.</p>



<p class="wp-block-paragraph">The issue is that the rule scopes view models by screens. But screens are a UI concern. What a view model actually manages is state, so that&#8217;s what should decide its scope.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">A Practical Approach: Scope by State, Not by Screen</h3>



<p class="wp-block-paragraph">Here are the guidelines I use instead:</p>



<ol class="wp-block-list">
<li><strong>Start from the state, not the screen.</strong> Ask: what state is this, and which views need it?</li>



<li><strong>Every piece of UI state has exactly one owner.</strong> One view model owns the cart. Not one per screen that shows the cart.</li>



<li><strong>Place the owner where the state needs to live.</strong> High enough in the view tree that every view that needs the state can reach it, and long-lived enough that the state survives as long as it should. If only one screen needs it, keep it there.</li>



<li><strong>Share the instance, don&#8217;t copy the state.</strong> Views that need the same state get the same view model passed in, and they all call the same methods to change it.</li>
</ol>



<p class="wp-block-paragraph">In the example above, <code>CartView</code> is short lived because its inside a sheet. It gets the ViewModel passed in from its parent. The product list needs it too. The ownership moves up: the app owns one <code>CartViewModel</code> and hands it to every view that needs it:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ContentView: View {
    @State private var cartViewModel = CartViewModel()
    @State private var cartIsShown = false
    
    var body: some View {
        ProductListView(cartViewModel, cartViewModel)
           .sheet(isShown: cartIsShown) {
               CartView(cartViewModel: cartViewModel)
            }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ContentView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> cartViewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">CartViewModel</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> cartIsShown </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">false</span></span>
<span class="line"><span style="color: #F6F6F4">    </span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">ProductListView</span><span style="color: #F6F6F4">(cartViewModel, cartViewModel)</span></span>
<span class="line"><span style="color: #F6F6F4">           .</span><span style="color: #97E1F1">sheet</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">isShown</span><span style="color: #F6F6F4">: cartIsShown) {</span></span>
<span class="line"><span style="color: #F6F6F4">               </span><span style="color: #97E1F1">CartView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">cartViewModel</span><span style="color: #F6F6F4">: cartViewModel)</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The product list adds an item, the badge updates, and the cart screen shows it, because they&#8217;re all looking at the same state, changed through the same methods.</p>



<p class="wp-block-paragraph">Notice that &#8220;one view model per screen&#8221; can still happen with this approach. If some state really belongs to only one screen, its view model naturally ends up there. The difference is that it&#8217;s a result of where the state belongs, not a rule you apply up front.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Drawing the Line: UI State vs. Background Work</h2>



<p class="wp-block-paragraph">In the cart example, everything happened locally. In a real app, adding an item to a cart probably means asking a server whether the item is still available. So where does that network code go? Into the view model?</p>



<p class="wp-block-paragraph">This is where one question helps you decide which layer code belongs to: <strong>does it own UI state?</strong></p>



<ul class="wp-block-list">
<li><strong>Yes → it&#8217;s a view model</strong> (or a store, whatever you want to call it). It&#8217;s <code>@Observable</code>, it runs on <code>@MainActor</code>, and views are connected to it.</li>



<li><strong>No → it belongs in a supporting layer behind the view model</strong>, like a service. It&#8217;s not observable, it&#8217;s not on the main actor, and it&#8217;s free to do its work in the background, for example with <code>@concurrent</code> functions.</li>
</ul>



<p class="wp-block-paragraph">This isn&#8217;t just a naming preference. It&#8217;s the reason I draw the line exactly here. Anything the UI needs to observe has to be observable and has to live on the main actor, because that&#8217;s where SwiftUI reads it. Anything that doesn&#8217;t touch UI state shouldn&#8217;t be there. Networking, decoding JSON, reading and writing files: that&#8217;s heavy work, and we want it off the main actor so the UI stays responsive.</p>


<div class="gb-container gb-container-979c67c2">

<figure class="gb-block-image gb-block-image-4cd9fbca"><img loading="lazy" decoding="async" width="1863" height="1056" class="gb-image gb-image-4cd9fbca" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/Presentation-Layer-Backing.webp" alt="" title="Presentation Layer - Backing" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/Presentation-Layer-Backing.webp 1863w, https://www.swiftyplace.com/wp-content/uploads/2026/10/Presentation-Layer-Backing-300x170.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/10/Presentation-Layer-Backing-1024x580.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/10/Presentation-Layer-Backing-768x435.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2026/10/Presentation-Layer-Backing-1536x871.webp 1536w" sizes="auto, (max-width: 1863px) 100vw, 1863px" /></figure>

</div>


<p class="wp-block-paragraph">The user taps a button. The view passes that intent to the view model. The view model asks the service to do the work in the background. The data comes back, the view model updates its UI state on the main actor, and SwiftUI updates the view.</p>



<p class="wp-block-paragraph">In code, the service is a small helper with no state of its own:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>nonisolated struct CartService {
    @concurrent
    func addItem(id: String) async throws -> &#91;CartItem&#93; {
        // Send the request, decode the response,
        // and return the cart as the server sees it
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">nonisolated</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">CartService</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@concurrent</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">addItem</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">id</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">throws</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> &#91;CartItem&#93; {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #7B7F8B">// Send the request, decode the response,</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #7B7F8B">// and return the cart as the server sees it</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">And the view model uses it, but stays in charge of the state:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@MainActor
@Observable
final class CartViewModel {
    private(set) var items: &#91;CartItem&#93; = []
    private(set) var errorMessage: String?
    private let service = CartService()

    func addItem(id: String) async {
        do {
            items = try await service.addItem(id: id)
        } catch {
            errorMessage = "Couldn't add the item. Please try again."
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F286C4">@Observable</span></span>
<span class="line"><span style="color: #F286C4">final</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">CartViewModel</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> items: &#91;CartItem&#93; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> errorMessage: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F286C4">?</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> service </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">CartService</span><span style="color: #F6F6F4">()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">addItem</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">id</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">do</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            items </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> service.</span><span style="color: #97E1F1">addItem</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">id</span><span style="color: #F6F6F4">: id)</span></span>
<span class="line"><span style="color: #F6F6F4">        } </span><span style="color: #F286C4">catch</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            errorMessage </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Couldn&#39;t add the item. Please try again.</span><span style="color: #DEE492">&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The service doesn&#8217;t know anything about the UI. The view model doesn&#8217;t know how the network request works. Each one has a clear job, and the boundary between them is exactly the boundary between the main actor and the background. This is good use of Separation of Concern principle (SoC).</p>



<p class="wp-block-paragraph">This also explains why naming matters. If something owns UI state, call it a view model or a store, even if someone labeled it a &#8220;service.&#8221; I see this a lot in code on GitHub and in blog posts: a &#8220;service&#8221; that holds UI state in a project that supposedly has no view models. It&#8217;s basically one, and the wrong name hides which code runs where and what the UI connects to.</p>



<p class="wp-block-paragraph">There&#8217;s more to say about this supporting layer, including the difference between services and repositories. I&#8217;ll cover that in a separate post.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">A View Model Is Not &#8220;All Business Logic&#8221;</h2>



<p class="wp-block-paragraph">You&#8217;ll often read that the view model is where your &#8220;business logic&#8221; goes. The problem is that &#8220;business logic&#8221; is a bag of everything. It doesn&#8217;t actually help you decide where a piece of code belongs.</p>



<p class="wp-block-paragraph">If you split it up, it becomes much clearer. Some business logic is about state: deciding what the UI should show and formatting data so it&#8217;s easy to display. That belongs in the view model. But a lot of business logic is about data access: network requests, file I/O, encoding and decoding. That belongs behind the view model, in the supporting layer.</p>



<p class="wp-block-paragraph">So instead of &#8220;the view model holds the business logic,&#8221; I&#8217;d put it this way: the view model holds the UI state and the logic that changes it. Everything else gets offloaded. This can lead to the dreaded &#8220;God&#8221; View Model, another mess we want to avoid.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">A Tool, Not a Rule</h2>



<p class="wp-block-paragraph">MVVM doesn&#8217;t mean you have to use a view model for every single view. In one of the original blog posts, Cooper and Peters made a point of saying they didn&#8217;t see it as a purist thing you apply everywhere. <strong>They saw it as a pattern that comes up naturally during development, something you reach for when the situation calls for it.</strong></p>



<p class="wp-block-paragraph">You always have the choice to keep all your code in the view. It&#8217;s your codebase. But when your views start piling up logic and state mutations, a view model is a very good tool to have.</p>



<p class="wp-block-paragraph">This brings us back to the argument that &#8220;the view is already the view model.&#8221; If you compare SwiftUI with WPF, where MVVM started, there are a lot of similarities: declarative UI, data bindings, reactive updates. And the goals are the same: keep your code organized, keep your views simple, and have clear rules for separating code into layers.</p>



<p class="wp-block-paragraph">So the argument is a bit strange when you think about it. Nobody ever said you <em>need</em> a view model. The real question is when one helps you, and in which situations.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Wrapping Up</h2>



<p class="wp-block-paragraph">Let&#8217;s bring it all together. A view model is a UI backing layer, and it&#8217;s defined by two things:</p>



<ul class="wp-block-list">
<li><strong>A single source of truth for UI state:</strong> the data your views need to render.</li>



<li><strong>A single source of state mutations:</strong> the methods responsible for changing that state properly and consistently.</li>
</ul>



<p class="wp-block-paragraph">Because it backs the UI, it&#8217;s <code>@Observable</code> and runs on <code>@MainActor</code>. Anything that doesn&#8217;t own UI state, like networking or file access, belongs in a supporting layer behind it, where it can do its work in the background.</p>



<p class="wp-block-paragraph">But a view model is also an extra layer, and every layer has a cost. In the next post, When to Use a View Model (and When It&#8217;s Overkill), we&#8217;ll look at concrete examples of when that cost is worth paying, and when a view-only solution is the better choice.</p>


<div class="gb-container gb-container-c5dedc2e">
<div class="gb-container gb-container-f7a433c7">
<div class="gb-container gb-container-7a8dc7a3">

<figure class="gb-block-image gb-block-image-f04fbbad"><a href="https://www.swiftyplace.com/free-swiftui-layout-cookbook" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" width="1446" height="1552" class="gb-image gb-image-f04fbbad" src="https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm.webp" alt="" title="lead magnet mvvm" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm.webp 1446w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-280x300.webp 280w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-954x1024.webp 954w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-768x824.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2026/10/lead-magnet-mvvm-1431x1536.webp 1431w" sizes="auto, (max-width: 1446px) 100vw, 1446px" /></a></figure>

</div>

<div class="gb-container gb-container-98352fe6">

<h4 class="gb-headline gb-headline-4aacd94c gb-headline-text">Get the MVVM SwiftUI Cheat Sheet</h4>



<p class="gb-headline gb-headline-5e6c4f85 gb-headline-text">The cheat sheet puts the whole system on a few pages: what goes in a view model, which view owns it, how to pass it down the tree, common mistakes, and code skeletons you can copy.</p>


<div class="gb-container gb-container-34a8ad02">

<a class="gb-button gb-button-63e90e76 gb-button-blue" href="https://school.swiftyplace.com/f/swiftui-mvvm-cheat-sheet" target="_blank" rel="noopener noreferrer"><span class="gb-button-text">Get the free cheat sheet</span><span class="gb-icon"><svg aria-hidden="true" role="img" height="1em" width="1em" viewBox="0 0 256 512" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M224.3 273l-136 136c-9.4 9.4-24.6 9.4-33.9 0l-22.6-22.6c-9.4-9.4-9.4-24.6 0-33.9l96.4-96.4-96.4-96.4c-9.4-9.4-9.4-24.6 0-33.9L54.3 103c9.4-9.4 24.6-9.4 33.9 0l136 136c9.5 9.4 9.5 24.6.1 34z"></path></svg></span></a>

</div>
</div>
</div>
</div><p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/swiftui-mvvm">What Is a View Model in SwiftUI MVVM, Really</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.swiftyplace.com/blog/swiftui-mvvm/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>What is @State actually doing in SwiftUI</title>
		<link>https://www.swiftyplace.com/blog/swiftui-state-property-wrapper?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=swiftui-state-property-wrapper</link>
					<comments>https://www.swiftyplace.com/blog/swiftui-state-property-wrapper#respond</comments>
		
		<dc:creator><![CDATA[Karin Prater]]></dc:creator>
		<pubDate>Tue, 22 Sep 2026 10:23:44 +0000</pubDate>
				<category><![CDATA[SwiftUI]]></category>
		<guid isPermaLink="false">https://www.swiftyplace.com/?p=1005694</guid>

					<description><![CDATA[<p>The SwiftUI property wrapper @State doesn't store values in your view struct. It creates a node in SwiftUI's AttributeGraph, and if you don't understand that, you'll write bugs you can't explain. Here's what's actually happening and how to fix the most common mistake.</p>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/swiftui-state-property-wrapper">What is @State actually doing in SwiftUI</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">When you write <code>@State private var count = 0</code> in a SwiftUI view, it looks like a normal property declaration. It&#8217;s not. That line doesn&#8217;t store a value inside your view struct. It tells SwiftUI to create a node in something called the <a href="https://www.swiftyplace.com/blog/the-attributegraph-the-engine-behind-every-swiftui-view" data-type="link" data-id="https://www.swiftyplace.com/blog/the-attributegraph-the-engine-behind-every-swiftui-view">AttributeGraph</a>. A runtime data structure that holds your actual state and tracks every dependency in your view hierarchy.</p>



<div style="height:63px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">The AttributeGraph</h2>



<p class="wp-block-paragraph">SwiftUI maintains an internal data structure called the AttributeGraph. It&#8217;s a directed graph where every node represents a value. A view&#8217;s body, a modifier, a piece of state, and the edges are the dependencies between them.</p>



<p class="wp-block-paragraph">When a state value changes, SwiftUI walks the edges to find exactly which nodes are affected and only reevaluates those. This is how SwiftUI decides whether your view&#8217;s body needs to run again. It&#8217;s not diffing a DOM. It&#8217;s tracking state dependencies.</p>



<p class="wp-block-paragraph">If you&#8217;ve ever opened Instruments and looked at the SwiftUI cause-and-effect graph, you&#8217;ve seen a slice of this. That&#8217;s the AttributeGraph. The nodes, the edges, the dependency chains. That&#8217;s what&#8217;s running your app.</p>



<div style="height:38px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">What does the @State Property Wrapper do?</h2>



<p class="wp-block-paragraph">When SwiftUI sees <code>@State</code>, it creates a node in the AttributeGraph to store this value. Here&#8217;s what that looks like in practice:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ParentView: View {
    // This creates a node in the AttributeGraph that holds the Int.
    // ParentView.body has a dependency edge to this node.
    @State private var counter = 0

    var body: some View {
        VStack {
            // `counter` flows into ChildView as an input — another edge in the graph.
            // When counter changes, SwiftUI walks the edges and knows
            // both ParentView.body and ChildView.body need reevaluation.
            ChildView(label: "You selected (counter)")
            Button("Increment: (counter)") { counter += 1 }
        }
    }
}

struct ChildView: View {
    let label: String  // an input edge from the parent's node
    var body: some View {
        Text(label)
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ParentView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// This creates a node in the AttributeGraph that holds the Int.</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// ParentView.body has a dependency edge to this node.</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> counter </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">VStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #7B7F8B">// `counter` flows into ChildView as an input — another edge in the graph.</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #7B7F8B">// When counter changes, SwiftUI walks the edges and knows</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #7B7F8B">// both ParentView.body and ChildView.body need reevaluation.</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">ChildView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">label</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">You selected (counter)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Button</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Increment: (counter)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) { counter </span><span style="color: #F286C4">+=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">1</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ChildView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> label: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">  </span><span style="color: #7B7F8B">// an input edge from the parent&#39;s node</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(label)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:23px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph"><code>@State</code> doesn&#8217;t store the value in <code>ParentView</code>. <code>ParentView</code> is a struct. A short-lived value type. It gets created, body gets evaluated, and it goes away. The actual <code>counter</code> value persists in the AttributeGraph across those struct lifetimes. The struct dies, the node in the graph doesn&#8217;t.</p>



<p class="wp-block-paragraph">If you&#8217;ve opened Instruments and looked at the cause and effect graph, you&#8217;ve seen a slice of this. That&#8217;s the AttributeGraph. The nodes, the edges, the dependency chains. That&#8217;s what&#8217;s running your app.</p>



<figure class="gb-block-image gb-block-image-5de8c37d"><img loading="lazy" decoding="async" width="1702" height="818" class="gb-image gb-image-5de8c37d" src="https://www.swiftyplace.com/wp-content/uploads/2026/09/swiftui-instrument-example-2-3.jpg" alt="" title="swiftui-instrument-example-2-3" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/09/swiftui-instrument-example-2-3.jpg 1702w, https://www.swiftyplace.com/wp-content/uploads/2026/09/swiftui-instrument-example-2-3-300x144.jpg 300w, https://www.swiftyplace.com/wp-content/uploads/2026/09/swiftui-instrument-example-2-3-1024x492.jpg 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/09/swiftui-instrument-example-2-3-768x369.jpg 768w, https://www.swiftyplace.com/wp-content/uploads/2026/09/swiftui-instrument-example-2-3-1536x738.jpg 1536w" sizes="auto, (max-width: 1702px) 100vw, 1702px" /></figure>



<p class="wp-block-paragraph">In the right sidebar, inside Instruments, you can see more details from the AttributeGraph and follow&nbsp;the updating process.</p>



<p class="wp-block-paragraph">(A) This is updating an existing view</p>



<p class="wp-block-paragraph">(B) The source node is a state node from ParentView._counter to</p>



<p class="wp-block-paragraph">(C) Destination ParentView.body</p>



<div style="height:54px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">What happens when you ignore this</h2>



<p class="wp-block-paragraph">This matters the moment you try to initialize <code>@State</code> from a parent value. You have a <code>NavigationSplitView</code>. The sidebar shows a list of users. When someone selects one, the detail pane loads that user&#8217;s profile. The detail view needs a <code>userID</code> from the parent to get started.</p>



<p class="wp-block-paragraph">The natural instinct is to initialize the view model in <code>init</code> and pass the value there:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct DetailView: View {
    @State private var viewModel: ViewModel

    init(userID: UUID) {
        _viewModel = State(wrappedValue: ViewModel(id: userID))
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">DetailView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> viewModel: ViewModel</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">init</span><span style="color: #F6F6F4">(</span><span style="color: #62E884; font-style: italic">userID</span><span style="color: #F6F6F4">: UUID) {</span></span>
<span class="line"><span style="color: #F6F6F4">        _viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">State</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">wrappedValue</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1">ViewModel</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">id</span><span style="color: #F6F6F4">: userID))</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:29px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">It works the first time. You select a user, the detail pane loads. Then you select a different user. The detail pane doesn&#8217;t update. It&#8217;s still showing the first user.</p>



<figure class="gb-block-image gb-block-image-3e77882a"><img loading="lazy" decoding="async" width="1544" height="396" class="gb-image gb-image-3e77882a" src="https://www.swiftyplace.com/wp-content/uploads/2026/09/state-init-pass-value-1.jpg" alt="" title="state-init-pass-value-1" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/09/state-init-pass-value-1.jpg 1544w, https://www.swiftyplace.com/wp-content/uploads/2026/09/state-init-pass-value-1-300x77.jpg 300w, https://www.swiftyplace.com/wp-content/uploads/2026/09/state-init-pass-value-1-1024x263.jpg 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/09/state-init-pass-value-1-768x197.jpg 768w, https://www.swiftyplace.com/wp-content/uploads/2026/09/state-init-pass-value-1-1536x394.jpg 1536w" sizes="auto, (max-width: 1544px) 100vw, 1544px" /></figure>



<div style="height:44px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Why it breaks</h2>



<p class="wp-block-paragraph">Let`s see, how the AttributeGraph looks behind these flow. First the selection is nil and no detail is shown:</p>



<figure class="gb-block-image gb-block-image-737fdeb1"><img loading="lazy" decoding="async" width="818" height="402" class="gb-image gb-image-737fdeb1" src="https://www.swiftyplace.com/wp-content/uploads/2026/09/Screenshot-2026-09-22-at-12.23.28-PM.png" alt="" title="Screenshot 2026-09-22 at 12.23.28 PM" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/09/Screenshot-2026-09-22-at-12.23.28-PM.png 818w, https://www.swiftyplace.com/wp-content/uploads/2026/09/Screenshot-2026-09-22-at-12.23.28-PM-300x147.png 300w, https://www.swiftyplace.com/wp-content/uploads/2026/09/Screenshot-2026-09-22-at-12.23.28-PM-768x377.png 768w" sizes="auto, (max-width: 818px) 100vw, 818px" /></figure>



<p class="wp-block-paragraph">Next selecting an item from the sidebar. The AttributeGraph adds a node for the new DetailView and stores the asscoated state with it:</p>



<figure class="gb-block-image gb-block-image-f92acc2c"><img loading="lazy" decoding="async" width="885" height="418" class="gb-image gb-image-f92acc2c" src="https://www.swiftyplace.com/wp-content/uploads/2026/09/Screenshot-2026-09-22-at-12.26.06-PM.png" alt="" title="Screenshot 2026-09-22 at 12.26.06 PM" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/09/Screenshot-2026-09-22-at-12.26.06-PM.png 885w, https://www.swiftyplace.com/wp-content/uploads/2026/09/Screenshot-2026-09-22-at-12.26.06-PM-300x142.png 300w, https://www.swiftyplace.com/wp-content/uploads/2026/09/Screenshot-2026-09-22-at-12.26.06-PM-768x363.png 768w" sizes="auto, (max-width: 885px) 100vw, 885px" /></figure>



<p class="wp-block-paragraph"><code>@State</code> creates a node in the AttributeGraph. SwiftUI reads the underscore syntax once. When that view identity is born. After that, the storage lives in the graph.</p>



<p class="wp-block-paragraph">When the parent passes a new <code>userID</code>, <code>init</code> runs again. <code>_viewModel = State(wrappedValue: ViewModel(id: newUserID))</code> executes. And SwiftUI throws the new value away. It already has a node for this identity. It doesn&#8217;t need a new one.</p>



<p class="wp-block-paragraph"><strong>You now have two sources of truth.</strong> The parent knows the selection changed. The child&#8217;s view model is still working with the old <code>userID</code>. They&#8217;re out of sync.</p>



<div style="height:47px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">The fix</h2>



<p class="wp-block-paragraph">Stop trying to re-initialize. React to the change instead. Pass <code>userID</code> as a plain property and let the view model own the response:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct DetailView: View {
    let userID: UUID
    @State private var viewModel: ViewModel?

    var body: some View {
        UserDetailContent(viewModel: viewModel)
            .task(id: userID) {
                if viewModel == nil {
                    viewModel = ViewModel()
                }
                await viewModel?.load(for: userID)
            }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">DetailView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> userID: UUID</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> viewModel: ViewModel</span><span style="color: #F286C4">?</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">UserDetailContent</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">viewModel</span><span style="color: #F6F6F4">: viewModel)</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">task</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">id</span><span style="color: #F6F6F4">: userID) {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> viewModel </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">nil</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                    viewModel </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">ViewModel</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">                }</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> viewModel</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">load</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">for</span><span style="color: #F6F6F4">: userID)</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph"><code>userID</code> is a plain property. An input edge in the graph. <code>@State</code> holds the view model as a node. <code>.task(id:)</code> fires whenever <code>userID</code> changes, including the first time the view appears. The view model is created once, and <code>load(for:)</code> handles every subsequent change.</p>



<p class="wp-block-paragraph">The parent owns the selected ID. The view model owns the loaded data. One source of truth on each side.</p>



<figure class="gb-block-image gb-block-image-37c02728"><img loading="lazy" decoding="async" width="1544" height="396" class="gb-image gb-image-37c02728" src="https://www.swiftyplace.com/wp-content/uploads/2026/09/state-init-pass-value-2.jpg" alt="" title="state-init-pass-value-2" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/09/state-init-pass-value-2.jpg 1544w, https://www.swiftyplace.com/wp-content/uploads/2026/09/state-init-pass-value-2-300x77.jpg 300w, https://www.swiftyplace.com/wp-content/uploads/2026/09/state-init-pass-value-2-1024x263.jpg 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/09/state-init-pass-value-2-768x197.jpg 768w, https://www.swiftyplace.com/wp-content/uploads/2026/09/state-init-pass-value-2-1536x394.jpg 1536w" sizes="auto, (max-width: 1544px) 100vw, 1544px" /></figure>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Going deeper</h2>



<p class="wp-block-paragraph">This example is from chapter 3 of <a href="https://school.swiftyplace.com/courses/swiftui-handbook-data-flow?coupon=SEPTEMBERRESET" data-type="link" data-id="https://school.swiftyplace.com/courses/swiftui-handbook-data-flow?coupon=SEPTEMBERRESET" target="_blank" rel="noopener">my book, SwiftUI Data Flow.</a> The whole book is built around understanding how the AttributeGraph, view identity, and state ownership actually work. Ao you can reason about your SwiftUI code instead of guessing.</p>



<p class="wp-block-paragraph">30% off until the end of September.</p>



<p class="wp-block-paragraph">Read about the <a href="https://www.swiftyplace.com/blog/the-attributegraph-the-engine-behind-every-swiftui-view" data-type="link" data-id="https://www.swiftyplace.com/blog/the-attributegraph-the-engine-behind-every-swiftui-view">AttributeGraph in this post</a>. </p>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/swiftui-state-property-wrapper">What is @State actually doing in SwiftUI</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.swiftyplace.com/blog/swiftui-state-property-wrapper/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>SwiftUI View Lifecycle: When onAppear Actually fires</title>
		<link>https://www.swiftyplace.com/blog/swiftui-view-lifecycle-onappear?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=swiftui-view-lifecycle-onappear</link>
					<comments>https://www.swiftyplace.com/blog/swiftui-view-lifecycle-onappear#comments</comments>
		
		<dc:creator><![CDATA[Karin Prater]]></dc:creator>
		<pubDate>Wed, 01 Apr 2026 08:04:28 +0000</pubDate>
				<category><![CDATA[SwiftUI]]></category>
		<guid isPermaLink="false">https://www.swiftyplace.com/?p=1005672</guid>

					<description><![CDATA[<p>In simple setups — a view behind an if condition, a sheet, a fullscreen cover — onAppear works exactly how you&#8217;d expect. Show the view, onAppear fires. Remove it, onDisappear fires. State is gone. Clean ... <a title="SwiftUI View Lifecycle: When onAppear Actually fires" class="read-more" href="https://www.swiftyplace.com/blog/swiftui-view-lifecycle-onappear" aria-label="More on SwiftUI View Lifecycle: When onAppear Actually fires">Read more</a></p>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/swiftui-view-lifecycle-onappear">SwiftUI View Lifecycle: When onAppear Actually fires</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-group is-vertical is-content-justification-left is-layout-flex wp-container-core-group-is-layout-fac2cdea wp-block-group-is-layout-flex">
<p class="wp-block-paragraph">In simple setups — a view behind an <code>if</code> condition, a sheet, a fullscreen cover — <code>onAppear</code> works exactly how you&#8217;d expect. Show the view, <code>onAppear</code> fires. Remove it, <code>onDisappear</code> fires. State is gone. Clean and predictable.</p>



<p class="wp-block-paragraph">Then you use <code>TabView</code>.</p>



<p class="wp-block-paragraph">You put a data fetch in <code>onAppear</code> on your second tab. On iOS 17, that fetch ran at app launch — even though the user was looking at the first tab. On iOS 18, same code, the fetch didn&#8217;t run until someone actually tapped the tab. Apple made <code>TabView</code> lazy. Same code. Different OS. Different behavior.</p>



<p class="wp-block-paragraph"><code>onAppear</code> has had genuinely unpredictable moments across SwiftUI&#8217;s lifetime — firing twice, firing in unexpected order, not firing when you&#8217;d swear it should. For an API that every app relies on, that&#8217;s a problem.</p>



<p class="wp-block-paragraph">So I spent time testing it properly, and I want to share what I found — because once you redefine one word, it all makes sense.</p>



<p class="wp-block-paragraph">The word is <strong>&#8220;appears.&#8221;</strong></p>



<p class="wp-block-paragraph"><em>This post builds on concepts from <a href="https://www.swiftyplace.com/blog/the-attributegraph-the-engine-behind-every-swiftui-view" data-type="post" data-id="1005648">The SwiftUI AttributeGraph</a>. If terms like &#8220;node,&#8221; &#8220;identity,&#8221; or &#8220;graph&#8221; are unfamiliar, start there.</em></p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-83393143"></div>
</div>



<div class="wp-block-group is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<h2 class="wp-block-heading">View Node Lifetime and Visibility</h2>



<p class="wp-block-paragraph">If you&#8217;ve read <a href="https://www.swiftyplace.com/blog/the-attributegraph-the-engine-behind-every-swiftui-view" data-type="post" data-id="1005648">The SwiftUI AttributeGraph</a>, you know that every view has a <strong>node</strong> in the graph — a slot that holds its <code>@State</code>, tracks its dependencies, and persists as long as the view&#8217;s identity exists in the tree.</p>



<p class="wp-block-paragraph">In order to understand when <code>onAppear</code> fires we need to look at 2 different concepts:</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-16d1eb73"></div>



<h3 class="wp-block-heading">Node Lifetime</h3>



<p class="wp-block-paragraph">When the node is <strong>created</strong> in the attribute graph and when it&#8217;s <strong>destroyed</strong>. This happens once per identity. When the node is created, <code>@State</code> gets its initial value. When the node is destroyed, that state is torn down. Gone.</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-16d1eb73"></div>



<h3 class="wp-block-heading">View Visibility</h3>



<p class="wp-block-paragraph">When a view becomes <strong>visible on screen</strong> and when it stops being visible. This can happen <strong>multiple times</strong> for the same node. A tab you switch away from disappears but its node can stay alive. A view inside a <code>NavigationStack</code> that gets covered by a push disappears but its node might still exist.</p>



<p class="wp-block-paragraph"><code>onAppear</code> doesn&#8217;t mean &#8220;this view was created.&#8221; It doesn&#8217;t mean &#8220;this view is new.&#8221; It means <strong>&#8220;this view just became visible.&#8221;</strong> And &#8220;visible&#8221; is doing all the heavy lifting.</p>



<p class="wp-block-paragraph"><code>@State</code> tracks <strong>lifetime</strong>. <code>onAppear</code>/<code>onDisappear</code> track <strong>visibility</strong>. They&#8217;re independent systems that sometimes align and sometimes don&#8217;t.</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>&nbsp;</th><th>What it tracks</th><th>How many times</th><th>What it affects</th></tr></thead><tbody><tr><td>Node lifetime</td><td>Creation/destruction in the graph</td><td>Once</td><td>lifetime of state (declared with <code>@State</code>, <code>@StateObject</code>)</td></tr><tr><td>View visibility</td><td>Visible/not visible on screen</td><td>Multiple times</td><td><code>onAppear</code>, <code>onDisappear</code>, <code>task</code></td></tr></tbody></table></figure>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-28f0cd9b"></div>
</div>



<div class="wp-block-group is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<h2 class="wp-block-heading">The Simple Case: When onAppear fires with conditional views</h2>



<p class="wp-block-paragraph">Here&#8217;s a case where lifetime and visibility happen at the same time, so everything feels intuitive:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ParentView: View {
    @State var showChild = true

    var body: some View {
        VStack {
            Toggle("Show Child", isOn: $showChild)
            if showChild {
                ChildView()
            }
        }
    }
}

struct ChildView: View {
    @State var userInput = ""

    var body: some View {
        TextField("Type something", text: $userInput)
            .onAppear { print("onAppear") }
            .onDisappear { print("onDisappear") }
            .task { print("task started") }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ParentView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> showChild </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">true</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">VStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Toggle</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Show Child</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">isOn</span><span style="color: #F6F6F4">: $showChild)</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> showChild {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">ChildView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ChildView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> userInput </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">TextField</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Type something</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">text</span><span style="color: #F6F6F4">: $userInput)</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">onAppear</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">onAppear</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">onDisappear</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">onDisappear</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">task</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">task started</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph">Try this:</p>



<ol class="wp-block-list">
<li>Type something into the text field</li>



<li>Toggle <code>showChild</code> to <code>false</code></li>



<li>Toggle it back to <code>true</code></li>
</ol>



<p class="wp-block-paragraph"><strong>Your text is gone.</strong></p>



<p class="wp-block-paragraph">Here&#8217;s what happened:</p>



<p class="wp-block-paragraph"><strong>Toggle off:</strong></p>



<ul class="wp-block-list">
<li>The <code>if</code> branch removes <code>ChildView</code> from the view tree</li>



<li>The node is destroyed — <code>@State userInput</code> is torn down</li>



<li><code>onDisappear</code> fires</li>



<li><code>task</code> is cancelled</li>
</ul>



<p class="wp-block-paragraph"><strong>Toggle on:</strong></p>



<ul class="wp-block-list">
<li>A new node is created — <code>@State userInput</code> is initialized fresh as <code>""</code></li>



<li><code>onAppear</code> fires</li>



<li><code>task</code> starts</li>
</ul>



<p class="wp-block-paragraph">One <code>onAppear</code> per lifetime. One <code>onDisappear</code> per lifetime. Lifetime and visibility are the same event. This is the case most tutorials show you, which is why you build the wrong mental model early.</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-c0740251"></div>
</div>



<div class="wp-block-group is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<h2 class="wp-block-heading">TabView: onAppear fires on every tab switch</h2>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ContentView: View {
    var body: some View {
        TabView {
            Tab("First", systemImage: "1.circle") {
                FirstTab()
            }
            Tab("Second", systemImage: "2.circle") {
                SecondTab()
            }
        }
    }
}

struct FirstTab: View {
    @State var userInput = ""
    var body: some View {
        Self._printChanges()
        return TextField("Type something", text: $userInput)
            .onAppear { print("FirstTab onAppear") }
            .onDisappear { print("FirstTab onDisappear") }
    }
}

struct SecondTab: View {
    var body: some View {
        Self._printChanges()
        return Text("Second tab")
            .onAppear { print("SecondTab onAppear") }
            .onDisappear { print("SecondTab onDisappear") }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ContentView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">TabView</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Tab</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">First</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">systemImage</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">1.circle</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">FirstTab</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Tab</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Second</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">systemImage</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">2.circle</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">SecondTab</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">FirstTab</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> userInput </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">Self</span><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">_printChanges</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">TextField</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Type something</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">text</span><span style="color: #F6F6F4">: $userInput)</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">onAppear</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">FirstTab onAppear</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">onDisappear</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">FirstTab onDisappear</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">SecondTab</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #BF9EEE; font-style: italic">Self</span><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">_printChanges</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Second tab</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">onAppear</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">SecondTab onAppear</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">onDisappear</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">SecondTab onDisappear</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph">Run this. Before you tap anything, look at the console:</p>



<pre class="wp-block-code"><code>FirstTab: @self, @identity, _userInput changed.
FirstTab onAppear</code></pre>



<p class="wp-block-paragraph">That&#8217;s it. Only the first tab. <code>SecondTab</code> didn&#8217;t print anything — no <code>onAppear</code>, no body call, no node created, nothing. It doesn&#8217;t exist yet. <code>TabView</code> only builds a tab when you navigate to it for the first time.</p>



<figure class="gb-block-image gb-block-image-19f990e7"><img loading="lazy" decoding="async" width="1546" height="956" class="gb-image gb-image-19f990e7" src="https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-first.webp" alt="" title="tabview-first" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-first.webp 1546w, https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-first-300x186.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-first-1024x633.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-first-768x475.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-first-1536x950.webp 1536w" sizes="auto, (max-width: 1546px) 100vw, 1546px" /></figure>



<p class="wp-block-paragraph">Now tap the second tab:</p>



<pre class="wp-block-code"><code>SecondTab: @self changed.
SecondTab onAppear
FirstTab onDisappear</code></pre>



<p class="wp-block-paragraph"><code>SecondTab</code>&#8216;s node is created now, its body is called. <code>FirstTab</code> disappears — but its node stays alive. I illustrated the visible view nodes in black and the &#8220;hidden&#8221; views in gray. I am not sure how this is exactly done in the AttributeGraph. I am guessing SwiftUI sets a flag on the nodes during <code>TabView</code> tab switching, which then triggers the<code> onAppear/onDisappear</code> calls that depend on this flag:</p>



<figure class="gb-block-image gb-block-image-d4d610a9"><img loading="lazy" decoding="async" width="1546" height="956" class="gb-image gb-image-d4d610a9" src="https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-second.webp" alt="" title="tabview-second" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-second.webp 1546w, https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-second-300x186.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-second-1024x633.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-second-768x475.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-second-1536x950.webp 1536w" sizes="auto, (max-width: 1546px) 100vw, 1546px" /></figure>



<p class="wp-block-paragraph">Tap back to the first tab:</p>



<pre class="wp-block-code"><code>FirstTab onAppear
SecondTab onDisappear</code></pre>



<p class="wp-block-paragraph"><code>FirstTab onAppear</code> fires again. But here&#8217;s the thing — <strong>if you typed something in that text field earlier, it&#8217;s still there.</strong> The node was never destroyed. <code>onAppear</code> fired because the view became visible again, not because it was recreated.</p>



<figure class="gb-block-image gb-block-image-ee4a97f5"><img loading="lazy" decoding="async" width="1546" height="956" class="gb-image gb-image-ee4a97f5" src="https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-third.webp" alt="" title="tabview-third" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-third.webp 1546w, https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-third-300x186.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-third-1024x633.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-third-768x475.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2026/03/tabview-third-1536x950.webp 1536w" sizes="auto, (max-width: 1546px) 100vw, 1546px" /></figure>



<p class="wp-block-paragraph">After you&#8217;ve visited both tabs, their nodes persist indefinitely. Switching tabs only triggers visibility events. Your <code>@State</code> in both tabs survives.</p>



<p class="wp-block-paragraph">This is the split in action. <code>onDisappear</code> fired, but the state survived. The node was never destroyed — the view just went off screen. <code>onAppear</code> and <code>onDisappear</code> responded to <strong>visibility</strong>. <code>@State</code> is tied to <strong>lifetime</strong>. In <code>TabView</code>, those are completely different timelines.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>iOS 17 note:</strong> In earlier versions, <code>TabView</code> built all tabs eagerly at launch. Your second tab&#8217;s <code>onAppear</code> would fire immediately — even though the user was looking at the first tab. If you had a data fetch in <code>onAppear</code> on a background tab, it ran at app launch. The lazy behavior described above is iOS 18+. Same code, different OS, different behavior. If you&#8217;re supporting iOS 17, account for both.</p>
</blockquote>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-6388d5dc"></div>
</div>



<div class="wp-block-group is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<h2 class="wp-block-heading">NavigationStack: onAppear fires during push/pop</h2>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ContentView: View {
    var body: some View {
        NavigationStack {
            RootView()
            .navigationDestination
        }
    }
}

struct RootView: View {
    var body: some View {
        NavigationLink("Go to Detail") {
            DetailView()
        }
        .onAppear { print("RootView onAppear") }
        .onDisappear { print("RootView onDisappear") }
    }
}

struct DetailView: View {
    @State var notes = ""

    var body: some View {
        TextField("Notes", text: $notes)
            .onAppear { print("DetailView onAppear") }
            .onDisappear { print("DetailView onDisappear") }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ContentView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">NavigationStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">RootView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">            .navigationDestination</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">RootView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">NavigationLink</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Go to Detail</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">DetailView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">onAppear</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">RootView onAppear</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">onDisappear</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">RootView onDisappear</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">DetailView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> notes </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">TextField</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Notes</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">text</span><span style="color: #F6F6F4">: $notes)</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">onAppear</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">DetailView onAppear</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">onDisappear</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">DetailView onDisappear</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph">Initially, you will see the root view. The AttributeGraph builds the view hierarchy for the NavigationStack:</p>


<div class="gb-container gb-container-d35b89ca">

<figure class="gb-block-image gb-block-image-d27bd351"><img loading="lazy" decoding="async" width="984" height="956" class="gb-image gb-image-d27bd351" src="https://www.swiftyplace.com/wp-content/uploads/2026/03/navstack-root.webp" alt="" title="navstack-root" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/03/navstack-root.webp 984w, https://www.swiftyplace.com/wp-content/uploads/2026/03/navstack-root-300x291.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/03/navstack-root-768x746.webp 768w" sizes="auto, (max-width: 984px) 100vw, 984px" /></figure>

</div>


<p class="wp-block-paragraph"><strong>Push to DetailView:</strong></p>



<ul class="wp-block-list">
<li><code>RootView</code>: <code>onDisappear</code> fires, node stays alive but becomes invisible (tagged grayed out in the AttributeGraph)</li>



<li><code>DetailView</code>: node created, <code>onAppear</code> fires</li>
</ul>


<div class="gb-container gb-container-ea1181b2">

<figure class="gb-block-image gb-block-image-1793812a"><img loading="lazy" decoding="async" width="1546" height="956" class="gb-image gb-image-1793812a" src="https://www.swiftyplace.com/wp-content/uploads/2026/03/navstack-detail.webp" alt="" title="navstack-detail" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/03/navstack-detail.webp 1546w, https://www.swiftyplace.com/wp-content/uploads/2026/03/navstack-detail-300x186.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/03/navstack-detail-1024x633.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/03/navstack-detail-768x475.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2026/03/navstack-detail-1536x950.webp 1536w" sizes="auto, (max-width: 1546px) 100vw, 1546px" /></figure>

</div>


<p class="wp-block-paragraph"><strong>Pop back:</strong></p>



<ul class="wp-block-list">
<li><code>DetailView</code>: <code>onDisappear</code> fires, <strong>node is destroyed</strong>, <code>@State notes</code> is gone</li>



<li><code>RootView</code>: <code>onAppear</code> fires, node was alive the whole time, state intact</li>
</ul>



<p class="wp-block-paragraph"><code>NavigationStack</code> <strong>destroys</strong> the node when you pop. <code>TabView</code> <strong>keeps</strong> it. Same <code>onDisappear</code> call, completely different lifetime behavior underneath.</p>



<p class="wp-block-paragraph">Push to <code>DetailView</code> again? Fresh node. <code>notes</code> starts again with the inital empty String.</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-28f0cd9b"></div>
</div>



<div class="wp-block-group is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<h2 class="wp-block-heading">List and LazyVStack: onAppear fires during scrolling</h2>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ContentView: View {
    var body: some View {
        List(0..&lt;1000) { index in
            RowView(index: index)
        }
    }
}

struct RowView: View {
    let index: Int
    @State var isExpanded = false

    var body: some View {
        Text("Row (index)")
            .padding(40)
            .onAppear { print("Row (index) onAppear") }
            .onDisappear { print("Row (index) onDisappear") }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ContentView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">List</span><span style="color: #F6F6F4">(</span><span style="color: #BF9EEE">0</span><span style="color: #F286C4">..&lt;</span><span style="color: #BF9EEE">1000</span><span style="color: #F6F6F4">) { index </span><span style="color: #F286C4">in</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">RowView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">index</span><span style="color: #F6F6F4">: index)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">RowView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> index: </span><span style="color: #97E1F1; font-style: italic">Int</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> isExpanded </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">false</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Row (index)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">padding</span><span style="color: #F6F6F4">(</span><span style="color: #BF9EEE">40</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">onAppear</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Row (index) onAppear</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">onDisappear</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Row (index) onDisappear</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>List</code> is lazy. It only creates nodes for visible rows. As you scroll:</p>



<ul class="wp-block-list">
<li>Rows scrolling <strong>into view</strong>: node created (or reconnected), <code>onAppear</code> fires</li>



<li>Rows scrolling <strong>out of view</strong>: <code>onDisappear</code> fires, node <strong>may be destroyed</strong> (SwiftUI decides based on memory pressure and caching)</li>
</ul>



<p class="wp-block-paragraph">This means <code>@State</code> inside a <code>List</code> row is <strong>unreliable</strong> for long-term storage. Scroll far enough away and come back — the node might have been destroyed and recreated. Your <code>isExpanded</code> resets to the initial value <code>false</code>.</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-c0740251"></div>
</div>



<div class="wp-block-group is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<h2 class="wp-block-heading">Where init Fits (It Doesn&#8217;t)</h2>



<p class="wp-block-paragraph">One more thing worth clarifying: init is not a lifecycle event.</p>



<p class="wp-block-paragraph">Your view struct&#8217;s init runs during the render pass — as part of SwiftUI evaluating the parent&#8217;s body. SwiftUI might evaluate your struct and decide nothing changed and skip rendering entirely.</p>



<p class="wp-block-paragraph">First render pass order (during launch):</p>



<pre class="wp-block-code"><code>1. Parent body evaluates
2. Child init runs (struct created)         ← @State is populated with initial values
3. Child body evaluates                     ← @State is read HERE
4. Layout is computed
5. onAppear fires                           
6. task starts                             
7. Rendering happens      
8. NOW on screen</code></pre>



<p class="wp-block-paragraph">later, when a state changes, these phases happen:</p>



<pre class="wp-block-code"><code>1. Parent body evaluates
2. Child init runs (struct created)         
3. Child body evaluates                     
4. Layout is computed                      
5. Rendering happens      
6. NOW on screen</code></pre>



<p class="wp-block-paragraph">You will see that body properties are recomputed and with it init of child views are called. Init calls happen often especially during hot paths (high frequency UI updates e.g. scroll animations). Don&#8217;t fetch data in init. Don&#8217;t start work in init. It&#8217;s not a signal that anything is happening — it&#8217;s SwiftUI trying to check for UI updates when state changes.</p>



<p class="wp-block-paragraph">And here&#8217;s a crash that comes directly from misunderstanding this order:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ItemListView: View {
    @State var items: &#91;String&#93; = []

    var body: some View {
        Text(items&#91;0&#93;) // <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a5.png" alt="💥" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Index out of range
            .onAppear {
                items = &#91;"Apple", "Banana", "Cherry"&#93;
            }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ItemListView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> items: &#91;</span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">&#93; </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> []</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(items&#91;</span><span style="color: #BF9EEE">0</span><span style="color: #F6F6F4">&#93;) </span><span style="color: #7B7F8B">// &#x1f4a5; Index out of range</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">onAppear</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                items </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> &#91;</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Apple</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Banana</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Cherry</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">&#93;</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph">This crashes. Look at the order above — body runs at step 3. onAppear runs at step 5. By the time onAppear populates the array, body has already tried to access items[0] on an empty array.</p>



<p class="wp-block-paragraph">The fix is to make your body handle the empty state:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>var body: some View {
    if let first = items.first {
        Text(first)
    } else {
        ProgressView()
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> first </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> items.</span><span style="color: #97E1F1">first</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(first)</span></span>
<span class="line"><span style="color: #F6F6F4">    } </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">ProgressView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph">Your body must be valid for the initial @State value. Always. onAppear, .task, and any async work all run after body has already been evaluated. If your initial state is an empty array, your body needs to handle an empty array. There&#8217;s no way to populate data &#8220;before&#8221; body runs — that&#8217;s not how the render pass works.</p>



<p class="wp-block-paragraph">The rule is simple: body runs before everything else. Your initial @State is all you have when body first evaluates. Design accordingly.</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-c0740251"></div>
</div>



<div class="wp-block-group is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<h2 class="wp-block-heading">What This Means for Production Code</h2>



<h3 class="wp-block-heading">Guard against multiple fetches</h3>



<p class="wp-block-paragraph"><code>onAppear</code> and <code>task</code> fires every time you switch back to a tab. Without a guard, you&#8217;re firing a network request every single time:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Fires on every tab switch
.task {
    await loadData()
}

// <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Only fetch if you don't already have data
.task {
    guard items.isEmpty else { return }
    await loadData()
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #7B7F8B">// &#x274c; Fires on every tab switch</span></span>
<span class="line"><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">task</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">loadData</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #7B7F8B">// &#x2705; Only fetch if you don&#39;t already have data</span></span>
<span class="line"><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">task</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">guard</span><span style="color: #F6F6F4"> items.</span><span style="color: #BF9EEE">isEmpty</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> { </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">loadData</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph">Or with a loading state:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>enum LoadingState {
    case idle, loading, loaded, failed(Error)
}

@State private var state: LoadingState = .idle

.task {
    guard state == .idle else { return }
    state = .loading
    do {
        items = try await api.fetchItems()
        state = .loaded
    } catch {
        state = .failed(error)
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">enum</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">LoadingState</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> idle, loading, loaded, failed(</span><span style="color: #97E1F1; font-style: italic">Error</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> state: LoadingState </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .idle</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">task</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">guard</span><span style="color: #F6F6F4"> state </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> .idle </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> { </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">    state </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .loading</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">do</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        items </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> api.</span><span style="color: #97E1F1">fetchItems</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        state </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .loaded</span></span>
<span class="line"><span style="color: #F6F6F4">    } </span><span style="color: #F286C4">catch</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        state </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .</span><span style="color: #97E1F1">failed</span><span style="color: #F6F6F4">(error)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph">With this safeguard in place, when the user switchs tabs, the system doesn&#8217;t re-fetch. The task fires, hits the guard, and exits.</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-c0740251"></div>



<h3 class="wp-block-heading">Distinguish &#8220;first load&#8221; from &#8220;came back&#8221;</h3>



<p class="wp-block-paragraph">Sometimes you want to do something every time the view appears (refresh a timestamp, check permissions) but only fetch data once:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@State private var hasLoaded = false

.task {
    if !hasLoaded {
        await loadData()
        hasLoaded = true
    }

    // Runs every appearance
    await refreshTimestamp()
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> hasLoaded </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">false</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">task</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">!</span><span style="color: #F6F6F4">hasLoaded {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">loadData</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        hasLoaded </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">true</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// Runs every appearance</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">refreshTimestamp</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>hasLoaded</code> is <code>@State</code> — tied to the node&#8217;s lifetime. It survives tab switches (visibility events) but resets if the node is destroyed (e.g., popped from a <code>NavigationStack</code>).</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-16d1eb73"></div>



<h3 class="wp-block-heading">Test with print statements before shipping</h3>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>.task {
    print("&#91;(Self.self)&#93; task fired")
    await loadData()
}
.onAppear { print("&#91;(Self.self)&#93; onAppear") }
.onDisappear { print("&#91;(Self.self)&#93; onDisappear") }</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">task</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">&#91;(Self.self)&#93; task fired</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">loadData</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">onAppear</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">&#91;(Self.self)&#93; onAppear</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span>
<span class="line"><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">onDisappear</span><span style="color: #F6F6F4"> { </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">&#91;(Self.self)&#93; onDisappear</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) }</span></span></code></pre></div>



<p class="wp-block-paragraph">Run your app. Switch tabs. Push and pop. Scroll. Watch the console. You&#8217;ll catch double-fetches, missing cancellations, and unexpected re-fires before your users do.</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-c0740251"></div>
</div>



<div class="wp-block-group is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<h2 class="wp-block-heading">Container Cheat Sheet</h2>



<p class="wp-block-paragraph">Because every container has different rules:</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>Container</th><th>Node created when&#8230;</th><th>Node destroyed when&#8230;</th><th><code>onAppear</code>/<code>onDisappear</code> fires on&#8230;</th></tr></thead><tbody><tr><td><code>if/else</code></td><td>Condition becomes true</td><td>Condition becomes false</td><td>Same as lifetime</td></tr><tr><td><code>TabView</code></td><td>Tab is first visited (lazy since iOS 18)</td><td>Rarely (app teardown)</td><td>Tab switch (visibility)</td></tr><tr><td><code>NavigationStack</code></td><td>Push</td><td>Pop</td><td>Push/pop (visibility)</td></tr><tr><td><code>List</code> / <code>LazyVStack</code></td><td>Row scrolls into view</td><td>Row scrolls far enough away (SwiftUI decides)</td><td>Scroll (visibility)</td></tr><tr><td><code>sheet</code> / <code>fullScreenCover</code></td><td>Presented</td><td>Dismissed</td><td>Same as lifetime</td></tr></tbody></table></figure>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-c0740251"></div>



<h2 class="wp-block-heading">The Mental Model</h2>



<p class="wp-block-paragraph">Stop thinking about SwiftUI lifecycle as a single linear sequence. Think about it as <strong>two independent tracks</strong>:</p>



<pre class="wp-block-code"><code>Node Lifetime: ─── created ───────────────────── destroyed 
                                       │                                                                                       │
                              @State initialized                                                            @State torn down                       


Visibility:           ───  visible ─── hidden ─── visible ───────── hidden                       
                                       │                   │                     │                                         │                       
                                   onAppear      onDisappear     onAppear                           onDisappear</code></pre>



<p class="wp-block-paragraph">In the <code>if/else</code> case, these tracks are the same length — one appear, one disappear, one lifetime. In <code>TabView</code>, the lifetime track is long and the visibility track bounces up and down within it.</p>



<p class="wp-block-paragraph">Once you see these as separate tracks, you stop being surprised when <code>onDisappear</code> fires but your state survives, or when <code>onAppear</code> fires but your <code>@State</code> isn&#8217;t fresh.</p>



<p class="wp-block-paragraph"></p>
</div>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/swiftui-view-lifecycle-onappear">SwiftUI View Lifecycle: When onAppear Actually fires</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.swiftyplace.com/blog/swiftui-view-lifecycle-onappear/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>The AttributeGraph &#8211; The Engine Behind Every SwiftUI View</title>
		<link>https://www.swiftyplace.com/blog/the-attributegraph-the-engine-behind-every-swiftui-view?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=the-attributegraph-the-engine-behind-every-swiftui-view</link>
					<comments>https://www.swiftyplace.com/blog/the-attributegraph-the-engine-behind-every-swiftui-view#comments</comments>
		
		<dc:creator><![CDATA[Karin Prater]]></dc:creator>
		<pubDate>Tue, 24 Mar 2026 14:19:05 +0000</pubDate>
				<category><![CDATA[iOS app development]]></category>
		<category><![CDATA[SwiftUI]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://www.swiftyplace.com/?p=1005648</guid>

					<description><![CDATA[<p>SwiftUI has been around since 2019. Apple has given us dozens of WWDC talks about it. And yet most developers — even experienced ones — still get tripped up by the same things: These aren&#8217;t ... <a title="The AttributeGraph &#8211; The Engine Behind Every SwiftUI View" class="read-more" href="https://www.swiftyplace.com/blog/the-attributegraph-the-engine-behind-every-swiftui-view" aria-label="More on The AttributeGraph &#8211; The Engine Behind Every SwiftUI View">Read more</a></p>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/the-attributegraph-the-engine-behind-every-swiftui-view">The AttributeGraph &#8211; The Engine Behind Every SwiftUI View</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-group is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<p class="wp-block-paragraph">SwiftUI has been around since 2019. Apple has given us dozens of WWDC talks about it. And yet most developers — even experienced ones — still get tripped up by the same things:</p>



<ul class="wp-block-list">
<li>Why does my @State initializer get ignored?</li>



<li>Why does my view&#8217;s state reset when I didn&#8217;t expect it to?</li>



<li>Where is deinit? When does my data actually get cleaned up?</li>



<li>Why did my entire list re-render when I changed one item?</li>
</ul>



<p class="wp-block-paragraph">These aren&#8217;t edge cases. They&#8217;re fundamental behaviors. And they all trace back to one thing that Apple barely talks about: the <strong>AttributeGraph</strong>.</p>



<p class="wp-block-paragraph">The AttributeGraph is SwiftUI&#8217;s runtime engine. It&#8217;s the thing that decides when your views update, what data persists, and what gets thrown away. Every SwiftUI behavior that confuses you is the graph doing exactly what it was designed to do.</p>



<p class="wp-block-paragraph">You don&#8217;t need to know its internal implementation. But you need to understand the <strong>model</strong> — how it thinks — because once you do, SwiftUI stops feeling like magic and starts feeling predictable.</p>


<div class="gb-container gb-container-d95462f4">

<figure class="gb-block-image gb-block-image-4605378c"><img loading="lazy" decoding="async" width="766" height="481" class="gb-image gb-image-4605378c" src="https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-6.webp" alt="" title="data-flow-tree-6" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-6.webp 766w, https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-6-300x188.webp 300w" sizes="auto, (max-width: 766px) 100vw, 766px" />
<figcaption class="gb-headline gb-headline-09b1863c gb-headline-text">source: <a href="https://www.google.com/url?sa=t&amp;source=web&amp;rct=j&amp;opi=89978449&amp;url=https://developer.apple.com/videos/play/wwdc2021/10022/&amp;ved=2ahUKEwiPpvWV3LiTAxXLR_EDHRKxDsMQwqsBegQIFRAB&amp;usg=AOvVaw11oMNT6BVU6LcnejX9Pkpj" data-type="link" data-id="https://www.google.com/url?sa=t&amp;source=web&amp;rct=j&amp;opi=89978449&amp;url=https://developer.apple.com/videos/play/wwdc2021/10022/&amp;ved=2ahUKEwiPpvWV3LiTAxXLR_EDHRKxDsMQwqsBegQIFRAB&amp;usg=AOvVaw11oMNT6BVU6LcnejX9Pkpj" target="_blank" rel="noopener">WWDC21 Demystify SwiftUI</a></figcaption>
</figure>

</div>


<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-81dc8709"></div>
</div>



<div class="wp-block-group has-f-6-f-6-f-4-color has-text-color is-vertical is-content-justification-left is-layout-flex wp-container-core-group-is-layout-fac2cdea wp-block-group-is-layout-flex">
<h2 class="gb-headline gb-headline-d5ed2bd9 gb-headline-text">What Is the AttributeGraph?</h2>



<p class="wp-block-paragraph">Think of a spreadsheet.</p>



<ul class="wp-block-list">
<li>Cell <strong>A1</strong> = <code>5</code></li>



<li>Cell <strong>A2</strong> = <code>10</code></li>



<li>Cell <strong>A3</strong> = <code>= A1 + A2</code></li>
</ul>



<p class="wp-block-paragraph">You change A1 to <code>7</code>. Excel doesn&#8217;t recalculate every cell in the sheet. It knows A3 depends on A1, so it recalculates <strong>only A3</strong>. A2 is untouched.</p>



<p class="wp-block-paragraph">The AttributeGraph works the same way. It&#8217;s a directed graph made up of:</p>



<ul class="wp-block-list">
<li><strong>Nodes</strong> (called <strong>attributes</strong>) — each one stores a specific piece of information. A <code>@State</code> value. A custom view. SwiftUI views like VStack, Text and Button. </li>



<li><strong>Edges</strong> (called <strong>dependencies</strong>) — connections between nodes that say &#8220;this node reads from that node.&#8221;</li>
</ul>



<p class="wp-block-paragraph">When a state node&#8217;s value changes, the graph walks <strong>down</strong> through the edges and marks every dependent node as <strong>dirty</strong> — meaning it needs to be recalculated. Nodes that don&#8217;t depend on the changed value are never touched.</p>



<p class="wp-block-paragraph">That&#8217;s the entire update engine.</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-c0740251"></div>
</div>



<div class="wp-block-group has-f-6-f-6-f-4-color has-text-color is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<h2 class="gb-headline gb-headline-1e1cf9e1 gb-headline-text">Your View Struct Is Not the UI</h2>



<p class="wp-block-paragraph">This is the most important mental shift coming from UIKit.</p>



<p class="wp-block-paragraph">In UIKit, your <code>UIViewController</code> <strong>is</strong> the thing. It holds the data. It holds the views. It has a lifecycle. You create it, you configure it, it lives, it dies.</p>



<p class="wp-block-paragraph">In SwiftUI, your view struct is a <strong>description</strong>. A blueprint. SwiftUI reads it, extracts the information, feeds it into the AttributeGraph, and throws the struct away.</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct CounterView: View {
    @State var count = 0

    var body: some View {
        VStack {
            Text("(count)")
            Button("+1") { count += 1 }
        }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">CounterView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> count </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">VStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">(count)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Button</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">+1</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) { count </span><span style="color: #F286C4">+=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">1</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph">When SwiftUI processes this, the graph ends up looking roughly like this:</p>


<div class="gb-container gb-container-a7db327a">

<figure class="gb-block-image gb-block-image-17bcf9ab"><img loading="lazy" decoding="async" width="736" height="648" class="gb-image gb-image-17bcf9ab" src="https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-1.webp" alt="" title="data-flow-tree-1" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-1.webp 736w, https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-1-300x264.webp 300w" sizes="auto, (max-width: 736px) 100vw, 736px" /></figure>

</div>


<p class="wp-block-paragraph">Each box is an attribute. Each arrow is a dependency. When <code>count</code> changes:</p>



<ol class="wp-block-list">
<li>The <code>count</code> attribute is marked dirty</li>



<li>All nodes that depend on count are marked as dirty (an edge/dependency from the state to): <code>ContentView</code> is marked dirty</li>



<li><code>CounterView.body</code> is called and compared (diff) against the old value</li>



<li><code>Text</code> depends on <code>body</code>&#8216;s output → <strong>the system notes the change</strong></li>



<li><code>Button</code> — did its inputs change? No → skipped</li>



<li>During the commit phase the acutual changes are passed to the underlying UIKit components: here a UILabel get a new text. </li>
</ol>



<p class="wp-block-paragraph">The view is used to create and update the underlying UI. </p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-29cb0303"></div>
</div>



<div class="wp-block-group has-f-6-f-6-f-4-color has-text-color is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<h2 class="gb-headline gb-headline-2c3b3666 gb-headline-text">Where @State Actually Lives</h2>



<p class="wp-block-paragraph">When you write:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>@State private var name = ""</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> name </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;&quot;</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>@State</code> is a property wrapper. Inside it, there&#8217;s a reference — Apple calls it a <code>_location</code> — that points to an attribute in the graph. The actual value lives <strong>there</strong>. I highlighted the state attribute as blue in the above infographic.</p>



<p class="wp-block-paragraph">Here&#8217;s what happens step by step when SwiftUI encounters your view for the first time:</p>



<pre class="wp-block-code"><code>1. Parent's body runs and mentions YourView(...)

2. SwiftUI calls YourView.init()
   → A temporary struct is created on the stack
   → @State property contains State&lt;String&gt;(initialValue: "")
   → This is just a DESCRIPTION — no storage yet

3. SwiftUI checks the view's position in the tree (Structural Identity)
   → "Have I seen a view at this position before?"

4. First time → NO
   → Allocate a new attribute in the graph
   → Store the initial value ""
   → Connect the @State handle to this attribute

5. SwiftUI calls body on the struct
   → body READS name
   → Graph records a dependency: "body depends on name"

6. SwiftUI throws away the struct
   → The struct is gone
   → The attribute in the graph remains</code></pre>



<p class="wp-block-paragraph">The struct is disposable. The state attribute in the graph is the source of truth.</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-c0740251"></div>
</div>



<div class="wp-block-group has-f-6-f-6-f-4-color has-text-color is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<h4 class="gb-headline gb-headline-51b632d5 gb-headline-text">Single Source of Truth: A Graph Topology</h4>


<div class="gb-container gb-container-">

<p class="wp-block-paragraph">You&#8217;ve heard this phrase a hundred times. Here&#8217;s what it means in terms of the graph.</p>

</div>


<p class="wp-block-paragraph"><strong>The Problem:</strong> Two @State = Two Attributes</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);--cbp-line-highlight-color:rgba(251, 251, 239, 0.2);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ParentView: View {
    @State var count = 0

    var body: some View {
        VStack {
            Button("+1") { count += 1 }
            ChildView(name: "Updated: (count)")
        }
    }
}

struct ChildView: View {
    @State var name: String

    var body: some View {
        Text(name) // Always shows "Updated: 0"
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ParentView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> count </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">VStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Button</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">+1</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) { count </span><span style="color: #F286C4">+=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">1</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">ChildView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">name</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Updated: (count)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ChildView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> name: </span><span style="color: #97E1F1; font-style: italic">String</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(name) </span><span style="color: #7B7F8B">// Always shows &quot;Updated: 0&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph">This creates <strong>two attributes</strong> in the graph, which i colored in blue:</p>


<div class="gb-container gb-container-ccb95118">

<figure class="gb-block-image gb-block-image-ac6af156"><img loading="lazy" decoding="async" width="1125" height="364" class="gb-image gb-image-ac6af156" src="http://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-tree.webp" alt="SwiftUI data flow with the attribute graph and state property wrapper" title="data-flow-tree-tree" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-tree.webp 1125w, https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-tree-300x97.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-tree-1024x331.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-tree-768x248.webp 768w" sizes="auto, (max-width: 1125px) 100vw, 1125px" /></figure>

</div>


<p class="wp-block-paragraph">The user taps the button. Only <code>ParentView.count</code> updates. <code>ChildView.name</code> is still <code>"Update 0"</code>. They have drifted apart. There is no edge connecting them for ongoing sync — the value was copied once at init and that&#8217;s it.</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-b0b89ccb"></div>



<p class="wp-block-paragraph"><strong>The Fix: </strong>One @State + @Binding = One Attribute</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);--cbp-line-highlight-color:rgba(251, 251, 239, 0.2);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ParentView: View {
    @State var count = 0

    var body: some View {
        VStack {
            Button("+1") { count += 1 }
            ChildView(name: "Updated: (count)")
        }
    }
}

struct ChildView: View {
    let name: String

    var body: some View {
        Text(name) 
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ParentView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> count </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">VStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Button</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">+1</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) { count </span><span style="color: #F286C4">+=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">1</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">ChildView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">name</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Updated: (count)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ChildView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> name: </span><span style="color: #97E1F1; font-style: italic">String</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(name) </span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>


<div class="gb-container gb-container-043252ec">

<figure class="gb-block-image gb-block-image-7a91f25b"><img loading="lazy" decoding="async" width="1125" height="364" class="gb-image gb-image-7a91f25b" src="https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-3.webp" alt="" title="data-flow-tree-3" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-3.webp 1125w, https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-3-300x97.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-3-1024x331.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-3-768x248.webp 768w" sizes="auto, (max-width: 1125px) 100vw, 1125px" /></figure>

</div>


<p class="wp-block-paragraph">There is only one <code>@State</code> declaration which SwiftUI interprets and creates one attribute for in the AttriibuteGraph. This one single source of truth that both <code>ParentView</code> and <code>ChildView</code> will reflect. </p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-c0740251"></div>
</div>



<div class="wp-block-group is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<h2 class="gb-headline gb-headline-ddce5427 gb-headline-text">Dependencies: How the Graph Knows What to Update</h2>



<p class="has-f-6-f-6-f-4-color has-text-color wp-block-paragraph">When your view<code> </code>is first time added to the view hierarchy, the system needs to add the edges/dependencies. The are differnt ways/styles that determine the rules. </p>



<p class="has-f-6-f-6-f-4-color has-text-color wp-block-paragraph">First lets look at value types with<code> @State</code> and <code>@Binding</code>:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct MyView: View {
    @State var name = ""       // @state create a node and the edge/dependency
    @Binding var name: String  // no edge, the updates are discovered during view tree walking 
    let age: Int               // no edge, the updates are discovered during view tree walking    

    var body: some View {
        Text(name) // body reads `name` but NOT `age`
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">MyView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> name </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;&quot;</span><span style="color: #F6F6F4">       </span><span style="color: #7B7F8B">// @state create a node and the edge/dependency</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Binding</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> name: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">  </span><span style="color: #7B7F8B">// no edge, the updates are discovered during view tree walking </span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> age: </span><span style="color: #97E1F1; font-style: italic">Int</span><span style="color: #F6F6F4">               </span><span style="color: #7B7F8B">// no edge, the updates are discovered during view tree walking    </span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(name) </span><span style="color: #7B7F8B">// body reads `name` but NOT `age`</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="has-f-6-f-6-f-4-color has-text-color wp-block-paragraph">Similarly for ObservableObject:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ParentView: View {
    @StateObject var myObject = MyObject()           // @StateObject create a node and the edge/dependency
    @StateObject var otherObject = OtherObject()     // @StateObject create a node and the edge/dependency
    var body: some View {
        MyView(myObject: myObject, otherObject: otherObject)
    }
}

struct MyView: View {
    @ObservedObject var myObject: MyObject          // edge to existing node 
    var otherObject: OtherObject                    // no edge, changes to this object will not be tracked

    var body: some View {
        Text(myObject.name) 
        Text(otherObject.count)
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ParentView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@StateObject</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> myObject </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">MyObject</span><span style="color: #F6F6F4">()           </span><span style="color: #7B7F8B">// @StateObject create a node and the edge/dependency</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@StateObject</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> otherObject </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">OtherObject</span><span style="color: #F6F6F4">()     </span><span style="color: #7B7F8B">// @StateObject create a node and the edge/dependency</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">MyView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">myObject</span><span style="color: #F6F6F4">: myObject, </span><span style="color: #97E1F1">otherObject</span><span style="color: #F6F6F4">: otherObject)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">MyView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@ObservedObject</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> myObject: MyObject          </span><span style="color: #7B7F8B">// edge to existing node </span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> otherObject: OtherObject                    </span><span style="color: #7B7F8B">// no edge, changes to this object will not be tracked</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(myObject.name) </span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(otherObject.</span><span style="color: #BF9EEE">count</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph">@StateObject tells the graph: <strong>&#8220;Allocate a persistent attribute for this object and keep it alive as long as this view&#8217;s identity exists.&#8221;</strong> Same rules as <code>@State</code> — created once, survives struct recreation, destroyed when identity is removed.</p>



<p class="wp-block-paragraph">SwiftUI sees the property wrappers and creates the edges in the AttributeGraph, which basically says &#8220;when any property in the ObservableObject changes, check these views for updates&#8221;. Note that without these property wrappers the graph has no pointer/edge and does not know to update this view. </p>



<p class="wp-block-paragraph">For Observable feature the rules are different. The edges are created towards the single properties in the Obervable and are set if they are accessed in the view:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ParentView: View {
    @State var myObject = MyObject()    // @StateObject create a node 
    var body: some View {
        MyView(myObject: myObject)     // no edge for dependency tracking,
                                       // because the body does not access any property
    }
}

struct MyView: View {
    var myObject: MyObject

    var body: some View {
        Text(myObject.name)    // read access -> edge to node "myObject.name" 
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ParentView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> myObject </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">MyObject</span><span style="color: #F6F6F4">()    </span><span style="color: #7B7F8B">// @StateObject create a node </span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">MyView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">myObject</span><span style="color: #F6F6F4">: myObject)     </span><span style="color: #7B7F8B">// no edge for dependency tracking,</span></span>
<span class="line"><span style="color: #F6F6F4">                                       </span><span style="color: #7B7F8B">// because the body does not access any property</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">MyView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> myObject: MyObject</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(myObject.name)    </span><span style="color: #7B7F8B">// read access -&gt; edge to node &quot;myObject.name&quot; </span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph">When using the new SwiftUI instrument feature, you will see the dependencies from the AttributeGraph. I gives you the `transactions` a list of state changes that is processed in batch per update frame. Then in blue the @State attributes and the edge/dependencies that are used from the AttributedGraph. It gives a lot of details like what views are further evaluatd and what SwiftUI views are updated e.g. Text views content. It basically shows you a part of the AttributeGraph and what state caused the upate and what views depend on it:</p>


<div class="gb-container gb-container-f2d6ddc6">

<figure class="gb-block-image gb-block-image-9d713ee4"><img loading="lazy" decoding="async" width="1064" height="462" class="gb-image gb-image-9d713ee4" src="http://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-4.webp" alt="SwiftUI cause and effects graph shows data dependencies" title="data-flow-tree-4" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-4.webp 1064w, https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-4-300x130.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-4-1024x445.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-4-768x333.webp 768w" sizes="auto, (max-width: 1064px) 100vw, 1064px" /></figure>

</div>


<p class="wp-block-paragraph">In this example, I am not only updating the view that directly depends on the state which is SubView, but also other views that recieve data from there parent views. SwiftUI is bacially &#8220;walking the tree&#8221; from top to botttom, which is also why the data flow is top to bottom from parent to child. But that is a different blog post on its own (when body is called, diff, and inits).</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-c0740251"></div>
</div>



<div class="wp-block-group is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<h2 class="wp-block-heading has-f-6-f-6-f-4-color has-text-color">When Does State Die?</h2>



<p class="has-f-6-f-6-f-4-color has-text-color wp-block-paragraph">In UIKit, you know exactly when data dies — <code>deinit</code>. You see it. You control it.</p>



<p class="has-f-6-f-6-f-4-color has-text-color wp-block-paragraph">In SwiftUI there&#8217;s no <code>deinit</code> on your view struct (it&#8217;s a value type — it just pops off the stack). So when does the graph clean up?</p>



<p class="has-f-6-f-6-f-4-color has-text-color wp-block-paragraph"><strong>When the view&#8217;s identity is removed from the tree.</strong></p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);--cbp-line-highlight-color:rgba(251, 251, 239, 0.2);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>struct ParentView: View {
    @State var showChild = true

    var body: some View {
        VStack {
            Toggle("Show", isOn: $showChild)
            if showChild {
                ChildView()
            }
        }
    }
}

struct ChildView: View {
    @State var count = 0

    var body: some View {
        Button("Count: (count)") { count += 1 }
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ParentView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> showChild </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">true</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">VStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Toggle</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Show</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">isOn</span><span style="color: #F6F6F4">: $showChild)</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> showChild {</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">ChildView</span><span style="color: #F6F6F4">()</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ChildView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@State</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> count </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Button</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Count: (count)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) { count </span><span style="color: #F286C4">+=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">1</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>


<div class="gb-container gb-container-7d1275fd">

<figure class="gb-block-image gb-block-image-9fae5fad"><img loading="lazy" decoding="async" width="1017" height="328" class="gb-image gb-image-9fae5fad" src="https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-5.webp" alt="" title="data-flow-tree-5" srcset="https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-5.webp 1017w, https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-5-300x97.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2026/03/data-flow-tree-5-768x248.webp 768w" sizes="auto, (max-width: 1017px) 100vw, 1017px" /></figure>

</div>


<ol class="wp-block-list has-f-6-f-6-f-4-color has-text-color">
<li><code>showChild</code> is <code>true</code>. <code>ChildView</code> appears. The graph creates an attribute for <code>count</code> with value <code>0</code>.</li>



<li>You tap the button a few times. <code>count</code> is now <code>5</code>.</li>



<li>Toggle <code>showChild</code> to <code>false</code>. The <code>if</code> branch removes <code>ChildView</code> from the tree.</li>



<li>SwiftUI sees that <code>ChildView</code>&#8216;s identity is gone → <strong>destroys all its attributes</strong>. <code>count</code> is gone.</li>



<li>Toggle <code>showChild</code> back to <code>true</code>. <code>ChildView</code> appears again. The graph creates a <strong>new</strong> attribute for <code>count</code> with value <code>0</code>.</li>
</ol>



<p class="has-f-6-f-6-f-4-color has-text-color wp-block-paragraph">The old <code>count = 5</code> is gone forever. This is your <code>deinit</code> — not on the struct, but on the <strong>identity in the graph</strong>.</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-16d1eb73"></div>
</div>



<div class="wp-block-group has-f-6-f-6-f-4-color has-text-color is-vertical is-content-justification-stretch is-layout-flex wp-container-core-group-is-layout-fb128502 wp-block-group-is-layout-flex">
<h2 class="gb-headline gb-headline-7e18e1fc gb-headline-text">Identity: How the Graph Knows &#8220;Which&#8221; View You Mean</h2>



<p class="wp-block-paragraph">The graph needs a way to match your view struct to the right attribute. It does this through <strong>Identity</strong>.</p>



<p class="wp-block-paragraph">There are two kinds:</p>



<h4 class="wp-block-heading">Structural Identity</h4>



<p class="wp-block-paragraph">This is the default. SwiftUI uses your view&#8217;s <strong>position in the code</strong> to identify it.</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>var body: some View {
    VStack {
        Text("Hello")   // ← identity: VStack/child-0
        Text("World")   // ← identity: VStack/child-1
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">VStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Hello</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)   </span><span style="color: #7B7F8B">// ← identity: VStack/child-0</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">World</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)   </span><span style="color: #7B7F8B">// ← identity: VStack/child-1</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph">Each <code>Text</code> has a different identity because it&#8217;s at a different position in the <code>VStack</code>. SwiftUI uses this position as the key to look up attributes in the graph.</p>



<p class="wp-block-paragraph">This is also why <code>if/else</code> branches create different identities:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>var body: some View {
    if isLoggedIn {
        HomeView()      // ← identity: if-true-branch
    } else {
        LoginView()     // ← identity: if-false-branch
    }
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> isLoggedIn {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">HomeView</span><span style="color: #F6F6F4">()      </span><span style="color: #7B7F8B">// ← identity: if-true-branch</span></span>
<span class="line"><span style="color: #F6F6F4">    } </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">LoginView</span><span style="color: #F6F6F4">()     </span><span style="color: #7B7F8B">// ← identity: if-false-branch</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph"><code>HomeView</code> and <code>LoginView</code> have completely different identities. They have completely different attributes in the graph. When <code>isLoggedIn</code> flips from <code>false</code> to <code>true</code>, the graph <strong>destroys</strong> all attributes for <code>LoginView</code> and <strong>creates</strong> new ones for <code>HomeView</code>.</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-16d1eb73"></div>



<h4 class="wp-block-heading">Explicit Identity</h4>



<p class="wp-block-paragraph">You provide this with <code>.id()</code> or <code>ForEach</code>.</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>ForEach(items, id: \.id) { item in
    RowView(item: item)
}</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #97E1F1">ForEach</span><span style="color: #F6F6F4">(items, </span><span style="color: #97E1F1">id</span><span style="color: #F6F6F4">: \.id) { item </span><span style="color: #F286C4">in</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #97E1F1">RowView</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">item</span><span style="color: #F6F6F4">: item)</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<p class="wp-block-paragraph">Each <code>RowView</code> is identified by <code>item.id</code>. If you remove an item from the array, the graph destroys the attributes for that identity. If you add a new item, new attributes are created.</p>



<p class="wp-block-paragraph">And here&#8217;s the power move:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><pre class="code-block-pro-copy-button-pre" aria-hidden="true"><textarea class="code-block-pro-copy-button-textarea" tabindex="-1" aria-hidden="true" readonly>ChildView()
    .id(someValue)</textarea></pre><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #97E1F1">ChildView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    .</span><span style="color: #97E1F1">id</span><span style="color: #F6F6F4">(someValue)</span></span></code></pre></div>



<p class="wp-block-paragraph">When <code>someValue</code> changes, SwiftUI treats this as a <strong>completely new view</strong>. The old attributes are destroyed. New ones are created with fresh initial values. This is your manual &#8220;reset state&#8221; button.</p>



<div style="height:0px" aria-hidden="true" class="wp-block-spacer wp-container-content-16d1eb73"></div>
</div>



<h2 class="gb-headline gb-headline-bb406d12 gb-headline-text">The Update Cycle: Putting It All Together</h2>



<p class="has-f-6-f-6-f-4-color has-text-color wp-block-paragraph">Here&#8217;s the full picture of what happens when you change a <code>@State</code> value:</p>



<pre class="wp-block-code has-f-6-f-6-f-4-color has-text-color"><code>1. You set count = 5
   → The @State handle writes to its attribute in the graph

2. The attribute marks itself as DIRTY

3. The graph walks DOWN through dependency edges
   → Every attribute that depends on `count` is marked dirty

4. SwiftUI schedules a re-evaluation (batched — not immediate)

5. On the next render pass, SwiftUI visits each dirty attribute
   → Calls body on views whose body attribute is dirty (starts in the highest node in the attribute graph, closest to @main)
   → body returns new view descriptions
   → diffing: compares old and new values to decide whats changed
   → markes custom views as invalide if there input changed
   → continuesly calls  body for invalidated subviews

6. Commit phase: changes are passed to the underlying rendering engine

7. Next frame: UI shows new display for updated state</code></pre>



<p class="has-f-6-f-6-f-4-color has-text-color wp-block-paragraph">This is why SwiftUI is fast. It doesn&#8217;t re-evaluate your entire view tree. It follows the dependency edges from the changed node downward and only touches what&#8217;s necessary. When it calls a body, it means it checks if it needs updating and only when it finds changes these are actually implemented. The whole system is very complex and Apple engineers have been working constantly on improving the reliability and performance of the system. </p>



<div style="height:25px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading has-f-6-f-6-f-4-color has-text-color">The UIKit <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2194.png" alt="↔" class="wp-smiley" style="height: 1em; max-height: 1em;" /> SwiftUI Translation Table</h2>



<figure class="wp-block-table"><table class="has-f-6-f-6-f-4-color has-text-color has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">Concept</th><th class="has-text-align-left" data-align="left">UIKit</th><th class="has-text-align-left" data-align="left">SwiftUI</th></tr></thead><tbody><tr><td class="has-text-align-left" data-align="left">Where data lives</td><td class="has-text-align-left" data-align="left">In your objects</td><td class="has-text-align-left" data-align="left">In the AttributeGraph</td></tr><tr><td class="has-text-align-left" data-align="left">Who creates UI</td><td class="has-text-align-left" data-align="left">You (<code>addSubview</code>, <code>NSLayoutConstraint</code>)</td><td class="has-text-align-left" data-align="left">The graph (from your <code>body</code> description)</td></tr><tr><td class="has-text-align-left" data-align="left">Who updates UI</td><td class="has-text-align-left" data-align="left">You (<code>label.text = ...</code>)</td><td class="has-text-align-left" data-align="left">The graph (dependency tracking)</td></tr><tr><td class="has-text-align-left" data-align="left">When data is created</td><td class="has-text-align-left" data-align="left"><code>init</code> / <code>viewDidLoad</code></td><td class="has-text-align-left" data-align="left">First time identity appears in tree</td></tr><tr><td class="has-text-align-left" data-align="left">When data dies</td><td class="has-text-align-left" data-align="left"><code>deinit</code></td><td class="has-text-align-left" data-align="left">Identity removed from tree</td></tr><tr><td class="has-text-align-left" data-align="left">How updates propagate</td><td class="has-text-align-left" data-align="left">You call methods manually</td><td class="has-text-align-left" data-align="left">Graph walks dependency edges automatically</td></tr><tr><td class="has-text-align-left" data-align="left">What your code is</td><td class="has-text-align-left" data-align="left">The engine</td><td class="has-text-align-left" data-align="left">A blueprint</td></tr></tbody></table></figure>



<div style="height:24px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading has-f-6-f-6-f-4-color has-text-color">Practical Implications</h2>



<p class="has-f-6-f-6-f-4-color has-text-color wp-block-paragraph">Everything above leads to a set of rules that aren&#8217;t suggestions — they&#8217;re consequences of how the graph works:</p>



<ol class="wp-block-list has-f-6-f-6-f-4-color has-text-color">
<li><p><strong>Don&#8217;t use <code>@State</code> for data passed from a parent.</strong> The graph allocates the attribute once and ignores future init values. Use <code>@Binding</code> or just a <code>let</code> constant.</p></li>



<li><p><strong>Don&#8217;t sync two <code>@State</code> properties manually.</strong> Two <code>@State</code> = two attributes. Use one <code>@State</code> and pass <code>@Binding</code> references down.</p></li>



<li><p><strong>Put your source of truth as low as possible, but high enough so that all views can access it.</strong> When an attribute changes, every dependent below it might be re-evaluated. If your <code>@State</code> is at the root, a change can cause many updated down the entire tree.</p></li>



<li><p><strong><code>@StateObject</code> for objects you create. <code>@ObservedObject</code> for objects you receive.</strong> This maps directly to whether the graph allocates storage or just watches.</p></li>



<li><p><strong><code>init()</code> is not your setup point.</strong> It runs every time the parent re-evaluates. The graph decides whether to use your initial values or ignore them.</p></li>
</ol>



<p class="wp-block-paragraph">Your view struct is the top layer. The graph is the middle layer. The screen is the output. You write the top layer. The graph does the rest.</p>



<p class="wp-block-paragraph">When something doesn&#8217;t behave the way you expect, the answer is almost always in the middle layer: which attribute exists, what it&#8217;s connected to, and whether its identity is still in the graph.</p>



<div style="height:41px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading has-f-6-f-6-f-4-color has-text-color">Further Reading</h2>



<ul class="wp-block-list has-f-6-f-6-f-4-color has-text-color">
<li><a href="https://developer.apple.com/documentation/swiftui/managing-user-interface-state" target="_blank" rel="noopener">Managing User Interface State — Apple Documentation</a></li>



<li><a href="https://developer.apple.com/videos/play/wwdc2021/10022/" target="_blank" rel="noopener">Demystify SwiftUI — WWDC21</a></li>



<li><a href="https://developer.apple.com/videos/play/wwdc2020/10040/" target="_blank" rel="noopener">Data Essentials in SwiftUI — WWDC20</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/the-attributegraph-the-engine-behind-every-swiftui-view">The AttributeGraph &#8211; The Engine Behind Every SwiftUI View</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.swiftyplace.com/blog/the-attributegraph-the-engine-behind-every-swiftui-view/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Building macOS Utility Apps with Command Line Tools</title>
		<link>https://www.swiftyplace.com/blog/building-macos-utiltiy-apps?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=building-macos-utiltiy-apps</link>
					<comments>https://www.swiftyplace.com/blog/building-macos-utiltiy-apps#comments</comments>
		
		<dc:creator><![CDATA[Karin Prater]]></dc:creator>
		<pubDate>Tue, 25 Feb 2025 12:57:50 +0000</pubDate>
				<category><![CDATA[macOS Development]]></category>
		<category><![CDATA[SwiftUI]]></category>
		<guid isPermaLink="false">https://www.swiftyplace.com/?p=1005387</guid>

					<description><![CDATA[<p>Hey there! Today I&#8217;m going to walk you through creating a practical macOS utility app that leverages the power of command line tools. If you&#8217;ve ever wanted to build your own menu bar utility that ... <a title="Building macOS Utility Apps with Command Line Tools" class="read-more" href="https://www.swiftyplace.com/blog/building-macos-utiltiy-apps" aria-label="More on Building macOS Utility Apps with Command Line Tools">Read more</a></p>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/building-macos-utiltiy-apps">Building macOS Utility Apps with Command Line Tools</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Hey there! Today I&#8217;m going to walk you through creating a practical macOS utility app that leverages the power of command line tools. If you&#8217;ve ever wanted to build your own menu bar utility that gives users helpful system information, this tutorial is for you.</p>



<p class="wp-block-paragraph">In this guide, I&#8217;ll show you how to build a Disk Analyzer app that sits in your menu bar, analyzes your disk space usage, and presents the information in a beautiful, user-friendly interface. We&#8217;ll combine SwiftUI&#8217;s modern interface capabilities with traditional Unix command line tools that have been part of macOS for decades.</p>



<p class="wp-block-paragraph"><a href="https://school.swiftyplace.com/f/macos-utilty-project-funnel" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2b07.png" alt="⬇" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong> Download project files</strong></a></p>



			
			
										
			
			


<div style="height:35px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">What Are Command Line Tools?</h2>



<p class="wp-block-paragraph">Before we dive into building our app, let me explain what command line tools are. If you&#8217;ve ever opened Terminal on your Mac, you&#8217;ve interacted with command line tools. These are powerful utilities that come built into macOS but don&#8217;t have a graphical interface. Instead, they&#8217;re typically run by typing commands into Terminal.</p>



<p class="wp-block-paragraph">The <code>df</code> command (which stands for &#8220;disk free&#8221;) is a utility that shows you how much disk space is available on your Mac. When we run it with the <code>-h</code> flag like this:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="df -h" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F6F6F4">df </span><span style="color: #F286C4">-</span><span style="color: #F6F6F4">h</span></span></code></pre></div>



<div style="height:23px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">When you add the -h, it shows the disk usage in human readable format. These tools are incredibly powerful but not very user-friendly for most people.</p>



<p class="wp-block-paragraph">Here&#8217;s what happens when you run <code>df</code> in Terminal:</p>



<figure class="gb-block-image gb-block-image-a2ae1fd4"><img loading="lazy" decoding="async" width="1626" height="795" class="gb-image gb-image-a2ae1fd4" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_terminal.webp" alt="" title="diskanalyser_app_terminal" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_terminal.webp 1626w, https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_terminal-300x147.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_terminal-1024x501.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_terminal-768x375.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_terminal-1536x751.webp 1536w" sizes="auto, (max-width: 1626px) 100vw, 1626px" /></figure>



<p class="wp-block-paragraph">The output is shown in a table style where the first line is the header. The morst important information is seen in &#8220;/Syste/Volumes/Data&#8221; line. The line meands that the size of the disk is 926GB of which 467GB is used.</p>



<p class="wp-block-paragraph">Not very pretty, right? But this is where we come in. As developers, we can create beautiful SwiftUI apps that use these command line tools behind the scenes while presenting the information in a way that&#8217;s easy to understand.</p>



<div style="height:41px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">What We&#8217;ll Build</h2>



<p class="wp-block-paragraph">In this tutorial, I&#8217;ll show you how to:</p>



<ol class="wp-block-list">
<li>Access command line tools from your SwiftUI app</li>



<li>Create a disk space analyzer using the <code>df</code> command</li>



<li>Present the information in a modern, user-friendly interface</li>
</ol>



<p class="wp-block-paragraph">The final app will look something like this:</p>



<figure class="gb-block-image gb-block-image-619bd497"><img loading="lazy" decoding="async" width="1718" height="1032" class="gb-image gb-image-619bd497" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_menu_bara.webp" alt="" title="diskanalyser_app_menu_bara" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_menu_bara.webp 1718w, https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_menu_bara-300x180.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_menu_bara-1024x615.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_menu_bara-768x461.webp 768w, https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_menu_bara-1536x923.webp 1536w" sizes="auto, (max-width: 1718px) 100vw, 1718px" /></figure>



<div style="height:52px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Getting Started: The App Structure</h2>



<p class="wp-block-paragraph">Let&#8217;s start by understanding the basic structure of our menu bar app. Unlike standard apps that open in a window, menu bar apps live in the system menu bar at the top of your screen.</p>



<p class="wp-block-paragraph">Here&#8217;s how we set up the basic app structure:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="import SwiftUI

@main
struct DiskAnalyserApp: App {
    var body: some Scene {
        MenuBarExtra(&quot;Disk Analyzer&quot;, systemImage: &quot;externaldrive.connected.to.line.below.fill&quot;) {
            ContentView()
                .frame(width: 400)
        }
        .menuBarExtraStyle(.window)
    }
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">import</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">SwiftUI</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">@main</span></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">DiskAnalyserApp</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">App </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> Scene {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">MenuBarExtra</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Disk Analyzer</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">systemImage</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">externaldrive.connected.to.line.below.fill</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">ContentView</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">                .</span><span style="color: #97E1F1">frame</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">width</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">400</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">menuBarExtraStyle</span><span style="color: #F6F6F4">(.window)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:24px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">This code creates a menu bar app with a disk icon. When clicked, it displays our <code>ContentView</code> in a small window with a fixed width of 400 points. The <code>.menuBarExtraStyle(.window)</code> modifier tells SwiftUI to display our content in a window-style dropdown rather than a traditional menu.</p>



<p class="wp-block-paragraph">I prefer this approach for utility apps because it gives users a familiar interface while keeping the app unobtrusive. The app doesn&#8217;t take up space in the Dock or App Switcher but is always just a click away in the menu bar.</p>



<div style="height:32px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Creating the Main Interface</h2>



<p class="wp-block-paragraph">Now let&#8217;s look at our main interface. This will be the content that appears when a user clicks on our menu bar icon.</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);--cbp-line-highlight-color:rgba(251, 251, 239, 0.2);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="import SwiftUI

struct ContentView: View {

    @StateObject private var fetcher = DiskInfoFetcher()

    var body: some View {
        LazyVStack(alignment: .leading, spacing: 20) {
            Text(&quot;Developer Disk Analyzer&quot;)
                .font(.title3)
                .bold()

            DiskInfoList(diskInfoFetcher: fetcher)
            DiskInfoChart(diskInfoFetcher: fetcher)
        }
        .padding(20)
        .onAppear {
            fetcher.loadDiskInfo()
        }
    }
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">import</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">SwiftUI</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">ContentView</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@StateObject</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> fetcher </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">DiskInfoFetcher</span><span style="color: #F6F6F4">()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">LazyVStack</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">alignment</span><span style="color: #F6F6F4">: .leading, </span><span style="color: #97E1F1">spacing</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">20</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Developer Disk Analyzer</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">                .</span><span style="color: #97E1F1">font</span><span style="color: #F6F6F4">(.title3)</span></span>
<span class="line"><span style="color: #F6F6F4">                .</span><span style="color: #97E1F1">bold</span><span style="color: #F6F6F4">()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">DiskInfoList</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">diskInfoFetcher</span><span style="color: #F6F6F4">: fetcher)</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">DiskInfoChart</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">diskInfoFetcher</span><span style="color: #F6F6F4">: fetcher)</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">padding</span><span style="color: #F6F6F4">(</span><span style="color: #BF9EEE">20</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">onAppear</span><span style="color: #F6F6F4"> {</span></span>
<span class="line cbp-line-highlight"><span style="color: #F6F6F4">            fetcher.</span><span style="color: #97E1F1">loadDiskInfo</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:28px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Our <code>ContentView</code> is straightforward. It creates a <code>DiskInfoFetcher</code> object (we&#8217;ll explore this in detail later), displays a title, and then shows two custom views: <code>DiskInfoList</code> and <code>DiskInfoChart</code>. When the view appears, it calls <code>loadDiskInfo()</code> to fetch the latest disk information.</p>



<p class="wp-block-paragraph">I&#8217;m using a <code>LazyVStack</code> here because it only renders the views when they&#8217;re needed, which can improve performance for complex UIs. For our small app, a regular <code>VStack</code> would work fine too, but I like to build with scalability in mind.</p>



<div style="height:28px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">The Heart of the App: Accessing Command Line Tools</h2>



<p class="wp-block-paragraph">Now let&#8217;s dive into the most interesting part of our app: using command line tools to gather system information. This is where macOS development offers unique opportunities that aren&#8217;t available on iOS.</p>



<p class="wp-block-paragraph">The <code>DiskInfoFetcher</code> class handles all the command line interactions:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="class DiskInfoFetcher: ObservableObject {

    enum CommandError: Error {
        case commandFailed(String)
        case parsingFailed
        case invalidData
        case emptyOutput
    }

    @Published private(set) var diskInfos = [FormattedDiskInfo]()
    @Published private(set) var isLoading = false
    @Published private(set) var error: Error?

    @MainActor
    func loadDiskInfo()  {
        isLoading = true

        Task {
            do {
                diskInfos = try await getDiskInfo()
                isLoading = false
            } catch {
                self.error = error
                isLoading = false
            }
        }
    }
    // More code follows...
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">class</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">DiskInfoFetcher</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">ObservableObject </span><span style="color: #F6F6F4">{</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">enum</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">CommandError</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Error </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> commandFailed(</span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> parsingFailed</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> invalidData</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> emptyOutput</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Published</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> diskInfos </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> [FormattedDiskInfo]()</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Published</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> isLoading </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">false</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@Published</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">private</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">set</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> error: </span><span style="color: #97E1F1; font-style: italic">Error</span><span style="color: #F286C4">?</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@MainActor</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">loadDiskInfo</span><span style="color: #F6F6F4">()  {</span></span>
<span class="line"><span style="color: #F6F6F4">        isLoading </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">true</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Task</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">do</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                diskInfos </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">getDiskInfo</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">                isLoading </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">false</span></span>
<span class="line"><span style="color: #F6F6F4">            } </span><span style="color: #F286C4">catch</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.</span><span style="color: #BF9EEE">error</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> error</span></span>
<span class="line"><span style="color: #F6F6F4">                isLoading </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">false</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// More code follows...</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:23px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">This class uses the <code>ObservableObject</code> protocol so our SwiftUI views can react to changes in the data. It publishes three properties:</p>



<ul class="wp-block-list">
<li><code>diskInfos</code>: The formatted disk information</li>



<li><code>isLoading</code>: A boolean indicating if we&#8217;re currently fetching data</li>



<li><code>error</code>: Any error that occurred during the fetch</li>
</ul>



<p class="wp-block-paragraph">The <code>loadDiskInfo()</code> method is marked with <code>@MainActor</code> to ensure UI updates happen on the main thread. It uses Swift&#8217;s modern concurrency system with <code>async</code>/<code>await</code> to fetch disk information without blocking the UI.</p>



<p class="wp-block-paragraph">Let&#8217;s look at how we actually execute command line tools:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="private func getDiskInfo() async throws -&gt; [FormattedDiskInfo] {
    try await Task.detached(priority: .userInitiated) {
        let output = try self.execute(&quot;df -k -P&quot;) // in kilo bytes
        print(output)
        let disks = try self.parseDfOutput(output)
        let formattedDisks = self.formateVolumes(for: disks)
        return formattedDisks
    }.value
}

private func execute(_ command: String) throws -&gt; String {
    let process = Process()
    let pipe = Pipe()

    process.standardOutput = pipe
    process.standardError = pipe
    process.arguments = [&quot;-c&quot;, command]
    process.executableURL = URL(fileURLWithPath: &quot;/bin/bash&quot;)

    try process.run()

    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    guard let output = String(data: data, encoding: .utf8) else {
        throw CommandError.invalidData
    }

    process.waitUntilExit()

    guard process.terminationStatus == 0 else {
        throw CommandError.commandFailed(output)
    }

    return output
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">getDiskInfo</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">async</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">throws</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> [FormattedDiskInfo] {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">await</span><span style="color: #F6F6F4"> Task.</span><span style="color: #97E1F1">detached</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">priority</span><span style="color: #F6F6F4">: .userInitiated) {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> output </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">execute</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">df -k -P</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) </span><span style="color: #7B7F8B">// in kilo bytes</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">print</span><span style="color: #F6F6F4">(output)</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> disks </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">parseDfOutput</span><span style="color: #F6F6F4">(output)</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> formattedDisks </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.</span><span style="color: #97E1F1">formateVolumes</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">for</span><span style="color: #F6F6F4">: disks)</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> formattedDisks</span></span>
<span class="line"><span style="color: #F6F6F4">    }.</span><span style="color: #BF9EEE">value</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">execute</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">command</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">throws</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> process </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">Process</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> pipe </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">Pipe</span><span style="color: #F6F6F4">()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    process.standardOutput </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> pipe</span></span>
<span class="line"><span style="color: #F6F6F4">    process.standardError </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> pipe</span></span>
<span class="line"><span style="color: #F6F6F4">    process.arguments </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> [</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">-c</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, command]</span></span>
<span class="line"><span style="color: #F6F6F4">    process.executableURL </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">URL</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">fileURLWithPath</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">/bin/bash</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">try</span><span style="color: #F6F6F4"> process.</span><span style="color: #97E1F1">run</span><span style="color: #F6F6F4">()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> data </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> pipe.fileHandleForReading.</span><span style="color: #97E1F1">readDataToEndOfFile</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">guard</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> output </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">data</span><span style="color: #F6F6F4">: data, </span><span style="color: #97E1F1">encoding</span><span style="color: #F6F6F4">: .</span><span style="color: #BF9EEE">utf8</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">throw</span><span style="color: #F6F6F4"> CommandError.invalidData</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    process.</span><span style="color: #97E1F1">waitUntilExit</span><span style="color: #F6F6F4">()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">guard</span><span style="color: #F6F6F4"> process.terminationStatus </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">throw</span><span style="color: #F6F6F4"> CommandError.</span><span style="color: #97E1F1">commandFailed</span><span style="color: #F6F6F4">(output)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> output</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:25px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The <code>getDiskInfo()</code> method runs in a detached task to avoid blocking the UI thread. It calls the Unix <code>df</code> command, which stands for &#8220;disk free&#8221; and reports file system disk space usage.</p>



<p class="wp-block-paragraph">In the <code>execute()</code> method, I&#8217;m using the <code>Process</code> and <code>Pipe</code> classes from Foundation to run shell commands and capture their output. This is a powerful technique that lets you leverage all the command line tools built into macOS.</p>



<p class="wp-block-paragraph">One important thing to note: I&#8217;m running the command through <code>/bin/bash</code> with the <code>-c</code> flag, which allows us to execute complex shell commands. For security reasons, you should be careful about what commands you run, especially if they include user input.</p>



<p class="wp-block-paragraph">The output is a text file that looks something like:</p>



<figure class="gb-block-image gb-block-image-5c22aaf7"><img loading="lazy" decoding="async" width="1212" height="443" class="gb-image gb-image-5c22aaf7" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_xocde_output.webp" alt="" title="diskanalyser_app_xocde_output" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_xocde_output.webp 1212w, https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_xocde_output-300x110.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_xocde_output-1024x374.webp 1024w, https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_xocde_output-768x281.webp 768w" sizes="auto, (max-width: 1212px) 100vw, 1212px" /></figure>



<div style="height:25px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Parsing Command Line Output</h2>



<p class="wp-block-paragraph">After executing the command, we need to parse its output into a usable format:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="private func parseDfOutput(_ output: String) throws -&gt; [DiskInfo] {
    let lines = output.components(separatedBy: .newlines)
    guard lines.count &gt; 1 else { throw CommandError.emptyOutput }

    // Skip header line
    let dataLines = lines.dropFirst()

    return dataLines.compactMap { line -&gt; DiskInfo? in
        let components = line.split(separator: &quot; &quot;, omittingEmptySubsequences: true)
        guard components.count &gt;= 5 else { return nil }

        return DiskInfo(
            filesystem: String(components[0]),
            size: Int64(components[1]) ?? 0,      // Now directly in KB
            used: Int64(components[2]) ?? 0,
            available: Int64(components[3]) ?? 0,
            capacity: Int(components[4].replacingOccurrences(of: &quot;%&quot;, with: &quot;&quot;)) ?? 0,
            mountPoint: components[5...].joined(separator: &quot; &quot;)
        )
    }
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">parseDfOutput</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">_</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">output</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">) </span><span style="color: #F286C4">throws</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> [DiskInfo] {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> lines </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> output.</span><span style="color: #97E1F1">components</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">separatedBy</span><span style="color: #F6F6F4">: .newlines)</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">guard</span><span style="color: #F6F6F4"> lines.</span><span style="color: #BF9EEE">count</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">&gt;</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">1</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> { </span><span style="color: #F286C4">throw</span><span style="color: #F6F6F4"> CommandError.emptyOutput }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// Skip header line</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> dataLines </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> lines.</span><span style="color: #97E1F1">dropFirst</span><span style="color: #F6F6F4">()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> dataLines.</span><span style="color: #97E1F1">compactMap</span><span style="color: #F6F6F4"> { line </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> DiskInfo</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">in</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> components </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> line.</span><span style="color: #97E1F1">split</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">separator</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98"> </span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">omittingEmptySubsequences</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">true</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">guard</span><span style="color: #F6F6F4"> components.</span><span style="color: #BF9EEE">count</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">&gt;=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">5</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> { </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">nil</span><span style="color: #F6F6F4"> }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">DiskInfo</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">filesystem</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4">(components[</span><span style="color: #BF9EEE">0</span><span style="color: #F6F6F4">]),</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">size</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Int64</span><span style="color: #F6F6F4">(components[</span><span style="color: #BF9EEE">1</span><span style="color: #F6F6F4">]) </span><span style="color: #F286C4">??</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span><span style="color: #F6F6F4">,      </span><span style="color: #7B7F8B">// Now directly in KB</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">used</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Int64</span><span style="color: #F6F6F4">(components[</span><span style="color: #BF9EEE">2</span><span style="color: #F6F6F4">]) </span><span style="color: #F286C4">??</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">available</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Int64</span><span style="color: #F6F6F4">(components[</span><span style="color: #BF9EEE">3</span><span style="color: #F6F6F4">]) </span><span style="color: #F286C4">??</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">capacity</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Int</span><span style="color: #F6F6F4">(components[</span><span style="color: #BF9EEE">4</span><span style="color: #F6F6F4">].</span><span style="color: #97E1F1">replacingOccurrences</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">of</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">%</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">with</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;&quot;</span><span style="color: #F6F6F4">)) </span><span style="color: #F286C4">??</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">mountPoint</span><span style="color: #F6F6F4">: components[</span><span style="color: #BF9EEE">5</span><span style="color: #F286C4">...</span><span style="color: #F6F6F4">].</span><span style="color: #97E1F1">joined</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">separator</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98"> </span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">        )</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The <code>df</code> command outputs a table of information. The first line is a header, and subsequent lines contain data about each filesystem. We split the output into lines, skip the header, and then parse each line into a <code>DiskInfo</code> object.</p>



<p class="wp-block-paragraph">This parsing logic is specific to the <code>df</code> command&#8217;s output format. If you&#8217;re working with a different command, you&#8217;ll need to adjust the parsing logic accordingly.</p>



<p class="wp-block-paragraph">After parsing the raw data, we format it for display:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="private func formateVolumes(for infos: [DiskInfo]) -&gt; [FormattedDiskInfo] {
   var results = [FormattedDiskInfo]()

    let total = infos.systemVolume?.size ?? 0

    let system = infos.systemVolume?.used ?? 0
    results.append(
        FormattedDiskInfo(title: &quot;System&quot;,
                            size: system,
                            totalSize: total)
    )

    let available = infos.systemVolume?.available ?? 0
    results.append(
        FormattedDiskInfo(title: &quot;Available&quot;,
                            size: available,
                            totalSize: total)
    )

    let userData = infos.dataVolume?.used ?? 0
    results.append(
        FormattedDiskInfo(title: &quot;User Data&quot;,
                            size: userData,
                            totalSize: total)
    )

   return results
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">private</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">func</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">formateVolumes</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">for</span><span style="color: #F6F6F4"> </span><span style="color: #FFB86C; font-style: italic">infos</span><span style="color: #F6F6F4">: [DiskInfo]) </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> [FormattedDiskInfo] {</span></span>
<span class="line"><span style="color: #F6F6F4">   </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> results </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> [FormattedDiskInfo]()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> total </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> infos.systemVolume</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4">.</span><span style="color: #BF9EEE">size</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">??</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> system </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> infos.systemVolume</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4">.used </span><span style="color: #F286C4">??</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"><span style="color: #F6F6F4">    results.</span><span style="color: #97E1F1">append</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">FormattedDiskInfo</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">title</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">System</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">                            </span><span style="color: #97E1F1">size</span><span style="color: #F6F6F4">: system,</span></span>
<span class="line"><span style="color: #F6F6F4">                            </span><span style="color: #97E1F1">totalSize</span><span style="color: #F6F6F4">: total)</span></span>
<span class="line"><span style="color: #F6F6F4">    )</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> available </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> infos.systemVolume</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4">.available </span><span style="color: #F286C4">??</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"><span style="color: #F6F6F4">    results.</span><span style="color: #97E1F1">append</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">FormattedDiskInfo</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">title</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Available</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">                            </span><span style="color: #97E1F1">size</span><span style="color: #F6F6F4">: available,</span></span>
<span class="line"><span style="color: #F6F6F4">                            </span><span style="color: #97E1F1">totalSize</span><span style="color: #F6F6F4">: total)</span></span>
<span class="line"><span style="color: #F6F6F4">    )</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> userData </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> infos.dataVolume</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4">.used </span><span style="color: #F286C4">??</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">0</span></span>
<span class="line"><span style="color: #F6F6F4">    results.</span><span style="color: #97E1F1">append</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">FormattedDiskInfo</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">title</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">User Data</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">                            </span><span style="color: #97E1F1">size</span><span style="color: #F6F6F4">: userData,</span></span>
<span class="line"><span style="color: #F6F6F4">                            </span><span style="color: #97E1F1">totalSize</span><span style="color: #F6F6F4">: total)</span></span>
<span class="line"><span style="color: #F6F6F4">    )</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">   </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> results</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">This method creates a simplified representation of the disk usage that&#8217;s easier for users to understand. Instead of showing every filesystem, we focus on the three categories most users care about: System, Available space, and User Data.</p>



<div style="height:39px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Data Models</h2>



<p class="wp-block-paragraph">Let&#8217;s take a quick look at our data models. First, the raw <code>DiskInfo</code> structure that closely matches the output of the <code>df</code> command:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="struct DiskInfo: Identifiable {
    let filesystem: String
    let size: Int64
    let used: Int64
    let available: Int64
    let capacity: Int
    let mountPoint: String

    var id: String { self.mountPoint }

    var isSystemVolume: Bool {
        mountPoint == &quot;/&quot;
    }

    var isDataVolume: Bool {
        mountPoint == &quot;/System/Volumes/Data&quot;
    }
}

// MARK: - Analysis Extension
extension Array where Element == DiskInfo {
    var systemVolume: DiskInfo? {
        first { $0.isSystemVolume }
    }

    var dataVolume: DiskInfo? {
        first { $0.isDataVolume }
    }
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">DiskInfo</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Identifiable </span><span style="color: #F6F6F4">{</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> filesystem: </span><span style="color: #97E1F1; font-style: italic">String</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> size: </span><span style="color: #97E1F1; font-style: italic">Int64</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> used: </span><span style="color: #97E1F1; font-style: italic">Int64</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> available: </span><span style="color: #97E1F1; font-style: italic">Int64</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> capacity: </span><span style="color: #97E1F1; font-style: italic">Int</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> mountPoint: </span><span style="color: #97E1F1; font-style: italic">String</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> id: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4"> { </span><span style="color: #BF9EEE; font-style: italic">self</span><span style="color: #F6F6F4">.mountPoint }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> isSystemVolume: </span><span style="color: #97E1F1; font-style: italic">Bool</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        mountPoint </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">/</span><span style="color: #DEE492">&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> isDataVolume: </span><span style="color: #97E1F1; font-style: italic">Bool</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        mountPoint </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">/System/Volumes/Data</span><span style="color: #DEE492">&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #7B7F8B">// MARK: - Analysis Extension</span></span>
<span class="line"><span style="color: #F286C4">extension</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Array</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">where</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Element</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">==</span><span style="color: #F6F6F4"> DiskInfo {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> systemVolume: DiskInfo</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">first</span><span style="color: #F6F6F4"> { </span><span style="color: #BF9EEE; font-style: italic">$0</span><span style="color: #F6F6F4">.isSystemVolume }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> dataVolume: DiskInfo</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">first</span><span style="color: #F6F6F4"> { </span><span style="color: #BF9EEE; font-style: italic">$0</span><span style="color: #F6F6F4">.isDataVolume }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:21px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">And then our user-friendly <code>FormattedDiskInfo</code> structure:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="struct FormattedDiskInfo: Identifiable {

    let id = UUID()
    let title: String
    let size: Int64
    let totalSize: Int64

    var percentage: Double {
        Double(size) / Double(totalSize)
    }

    var formattedSize: String {
        ByteCountFormatter.string(fromByteCount: size * 1024, countStyle: .file)
    }

    var formattedTotalSize: String {
        ByteCountFormatter.string(fromByteCount: totalSize * 1024, countStyle: .file)
    }

    static var example: FormattedDiskInfo {
        FormattedDiskInfo(title: &quot;System&quot;,
                          size: 11 * 1024,
                          totalSize: 924 * 1024)
    }
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">FormattedDiskInfo</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">Identifiable </span><span style="color: #F6F6F4">{</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> id </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1">UUID</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> title: </span><span style="color: #97E1F1; font-style: italic">String</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> size: </span><span style="color: #97E1F1; font-style: italic">Int64</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> totalSize: </span><span style="color: #97E1F1; font-style: italic">Int64</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> percentage: </span><span style="color: #97E1F1; font-style: italic">Double</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1; font-style: italic">Double</span><span style="color: #F6F6F4">(size) </span><span style="color: #F286C4">/</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Double</span><span style="color: #F6F6F4">(totalSize)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> formattedSize: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        ByteCountFormatter.</span><span style="color: #97E1F1">string</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">fromByteCount</span><span style="color: #F6F6F4">: size </span><span style="color: #F286C4">*</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">1024</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">countStyle</span><span style="color: #F6F6F4">: .file)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> formattedTotalSize: </span><span style="color: #97E1F1; font-style: italic">String</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        ByteCountFormatter.</span><span style="color: #97E1F1">string</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">fromByteCount</span><span style="color: #F6F6F4">: totalSize </span><span style="color: #F286C4">*</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">1024</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">countStyle</span><span style="color: #F6F6F4">: .file)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">static</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> example: FormattedDiskInfo {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">FormattedDiskInfo</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">title</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">System</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">                          </span><span style="color: #97E1F1">size</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">11</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">*</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">1024</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">                          </span><span style="color: #97E1F1">totalSize</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">924</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">*</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">1024</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:22px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">I&#8217;ve added computed properties to calculate percentages and format byte counts into human-readable strings. The <code>ByteCountFormatter</code> is a great Foundation class that handles the complexity of displaying file sizes in appropriate units (KB, MB, GB, etc.).</p>



<div style="height:36px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Building the UI Components for macOS with SwiftUI</h2>



<p class="wp-block-paragraph">Now let&#8217;s look at how we display this information. First, the list view:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="struct DiskInfoList: View {

    @ObservedObject var diskInfoFetcher: DiskInfoFetcher

    var body: some View {
        GroupBox {
            VStack(alignment: .leading, spacing: 8) {
                if diskInfoFetcher.isLoading {
                    ProgressView(&quot;Analyzing disk space...&quot;)
                        .padding()
                        .frame(maxWidth: .infinity)
                } else if let error = diskInfoFetcher.error {
                    Text(&quot;Error: (error.localizedDescription)&quot;)
                        .foregroundStyle(.pink)
                        .padding()
                } else {

                    if let disk = diskInfoFetcher.diskInfos.first {
                        HStack {
                            Text(&quot;Your total disk space:&quot;)
                            Spacer()
                            Text(disk.formattedTotalSize)
                                .font(.system(.body, design: .monospaced))
                        }
                        Divider()
                    }

                    ForEach(diskInfoFetcher.diskInfos) { disk in
                        DiskInfoRow(diskInfo: disk)
                    }
                }
            }
        } label: {
            HStack {
                Text(&quot;Disk Space Overview&quot;)

                Spacer()

                Image(systemName: &quot;externaldrive.fill.trianglebadge.exclamationmark&quot;)
                    .renderingMode(.template)
                    .foregroundStyle(.orange)

                Text(&quot;Only Updated Once a Day&quot;)
            }
        }
    }
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">DiskInfoList</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@ObservedObject</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> diskInfoFetcher: DiskInfoFetcher</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">GroupBox</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">VStack</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">alignment</span><span style="color: #F6F6F4">: .leading, </span><span style="color: #97E1F1">spacing</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">8</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> diskInfoFetcher.isLoading {</span></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">ProgressView</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Analyzing disk space...</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">                        .</span><span style="color: #97E1F1">padding</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">                        .</span><span style="color: #97E1F1">frame</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">maxWidth</span><span style="color: #F6F6F4">: .</span><span style="color: #BF9EEE">infinity</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">                } </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> error </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> diskInfoFetcher.</span><span style="color: #BF9EEE">error</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Error: (error.localizedDescription)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">                        .</span><span style="color: #97E1F1">foregroundStyle</span><span style="color: #F6F6F4">(.pink)</span></span>
<span class="line"><span style="color: #F6F6F4">                        .</span><span style="color: #97E1F1">padding</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">                } </span><span style="color: #F286C4">else</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> disk </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> diskInfoFetcher.diskInfos.</span><span style="color: #97E1F1">first</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                        </span><span style="color: #97E1F1">HStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                            </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Your total disk space:</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">                            </span><span style="color: #97E1F1">Spacer</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">                            </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(disk.formattedTotalSize)</span></span>
<span class="line"><span style="color: #F6F6F4">                                .</span><span style="color: #97E1F1">font</span><span style="color: #F6F6F4">(.</span><span style="color: #97E1F1">system</span><span style="color: #F6F6F4">(.body, </span><span style="color: #97E1F1">design</span><span style="color: #F6F6F4">: .monospaced))</span></span>
<span class="line"><span style="color: #F6F6F4">                        }</span></span>
<span class="line"><span style="color: #F6F6F4">                        </span><span style="color: #97E1F1">Divider</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">                    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">ForEach</span><span style="color: #F6F6F4">(diskInfoFetcher.diskInfos) { disk </span><span style="color: #F286C4">in</span></span>
<span class="line"><span style="color: #F6F6F4">                        </span><span style="color: #97E1F1">DiskInfoRow</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">diskInfo</span><span style="color: #F6F6F4">: disk)</span></span>
<span class="line"><span style="color: #F6F6F4">                    }</span></span>
<span class="line"><span style="color: #F6F6F4">                }</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        } </span><span style="color: #97E1F1">label</span><span style="color: #F6F6F4">: {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">HStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Disk Space Overview</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">Spacer</span><span style="color: #F6F6F4">()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">Image</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">systemName</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">externaldrive.fill.trianglebadge.exclamationmark</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">                    .</span><span style="color: #97E1F1">renderingMode</span><span style="color: #F6F6F4">(.template)</span></span>
<span class="line"><span style="color: #F6F6F4">                    .</span><span style="color: #97E1F1">foregroundStyle</span><span style="color: #F6F6F4">(.orange)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Only Updated Once a Day</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:26px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">This view handles three states:</p>



<ol class="wp-block-list">
<li>Loading: Shows a progress indicator</li>



<li>Error: Displays the error message</li>



<li>Success: Shows the total disk space and a list of disk info rows</li>
</ol>



<p class="wp-block-paragraph">I&#8217;m using a <code>GroupBox</code> to visually group the information, which is a common pattern in macOS apps. The label includes a warning that the information is only updated once a day, which is a good practice to set user expectations.</p>



<div style="height:26px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="gb-block-image gb-block-image-998b918d"><img loading="lazy" decoding="async" width="766" height="354" class="gb-image gb-image-998b918d" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_overview.webp" alt="" title="diskanalyser_app_overview" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_overview.webp 766w, https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_overview-300x139.webp 300w" sizes="auto, (max-width: 766px) 100vw, 766px" /></figure>



<div style="height:36px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Each row in the list is handled by a separate view:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="struct DiskInfoRow: View {

    let diskInfo: FormattedDiskInfo

    var body: some View {
        VStack(spacing: 4) {
            HStack {
                Text(diskInfo.title)
                    .font(.system(.body, design: .rounded))
                Spacer()
                Text(diskInfo.formattedSize)
                    .font(.system(.body, design: .monospaced))
            }

            GeometryReader { geometry in
                ZStack(alignment: .leading) {
                    Rectangle()
                        .fill(Color.gray.opacity(0.2))

                    Rectangle()
                        .fill(progressColor)
                        .frame(width: geometry.size.width * diskInfo.percentage)
                }
            }
            .frame(height: 6)
            .clipShape(RoundedRectangle(cornerRadius: 3))
        }
    }

    var progressColor: Color {
        switch diskInfo.title {
            case &quot;System&quot;: return .blue
            case &quot;Available&quot;: return .green
            default: return .orange
        }
    }
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">DiskInfoRow</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> diskInfo: FormattedDiskInfo</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">VStack</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">spacing</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">4</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">HStack</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(diskInfo.title)</span></span>
<span class="line"><span style="color: #F6F6F4">                    .</span><span style="color: #97E1F1">font</span><span style="color: #F6F6F4">(.</span><span style="color: #97E1F1">system</span><span style="color: #F6F6F4">(.body, </span><span style="color: #97E1F1">design</span><span style="color: #F6F6F4">: .rounded))</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">Spacer</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(diskInfo.formattedSize)</span></span>
<span class="line"><span style="color: #F6F6F4">                    .</span><span style="color: #97E1F1">font</span><span style="color: #F6F6F4">(.</span><span style="color: #97E1F1">system</span><span style="color: #F6F6F4">(.body, </span><span style="color: #97E1F1">design</span><span style="color: #F6F6F4">: .monospaced))</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">GeometryReader</span><span style="color: #F6F6F4"> { geometry </span><span style="color: #F286C4">in</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">ZStack</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">alignment</span><span style="color: #F6F6F4">: .leading) {</span></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">Rectangle</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">                        .</span><span style="color: #97E1F1">fill</span><span style="color: #F6F6F4">(Color.gray.</span><span style="color: #97E1F1">opacity</span><span style="color: #F6F6F4">(</span><span style="color: #BF9EEE">0.2</span><span style="color: #F6F6F4">))</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">Rectangle</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">                        .</span><span style="color: #97E1F1">fill</span><span style="color: #F6F6F4">(progressColor)</span></span>
<span class="line"><span style="color: #F6F6F4">                        .</span><span style="color: #97E1F1">frame</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">width</span><span style="color: #F6F6F4">: geometry.</span><span style="color: #BF9EEE">size</span><span style="color: #F6F6F4">.width </span><span style="color: #F286C4">*</span><span style="color: #F6F6F4"> diskInfo.percentage)</span></span>
<span class="line"><span style="color: #F6F6F4">                }</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">frame</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">height</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">6</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">clipShape</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">RoundedRectangle</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">cornerRadius</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">3</span><span style="color: #F6F6F4">))</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> progressColor: Color {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">switch</span><span style="color: #F6F6F4"> diskInfo.title {</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">System</span><span style="color: #DEE492">&quot;</span><span style="color: #F286C4">:</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> .blue</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">case</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Available</span><span style="color: #DEE492">&quot;</span><span style="color: #F286C4">:</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> .green</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #F286C4">default:</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> .orange</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:32px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Each row shows the title, size, and a progress bar indicating what percentage of the total disk space this category occupies. I&#8217;m using different colors for each category to make the visualization more intuitive.</p>



<p class="wp-block-paragraph">Finally, let&#8217;s look at the chart view:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="import SwiftUI
import Charts

struct DiskInfoChart: View {

    @ObservedObject var diskInfoFetcher: DiskInfoFetcher

    var body: some View {
        Chart(diskInfoFetcher.diskInfos) { info in
            SectorMark(
                angle: .value(
                    Text(verbatim: info.title),
                    info.percentage
                ),
                innerRadius: .ratio(0.6),
                angularInset: 1.0
            )
            .foregroundStyle(
                by: .value(
                    Text(verbatim: info.title),
                    info.title
                )
            )

            .cornerRadius(3)
            .annotation(position: .overlay) {
                if info.title != &quot;System&quot; {
                    Text(&quot;(info.percentage * 100, specifier: &quot;%.1f%%&quot;)&quot;)
                        .bold()
                }
            }
        }
        .chartLegend(position: .trailing, alignment: .center)
        .frame(height: 120)
        .padding(.trailing, 70)
        .frame(maxWidth: .infinity, alignment: .center)
    }
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">import</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">SwiftUI</span></span>
<span class="line"><span style="color: #F286C4">import</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Charts</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">struct</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">DiskInfoChart</span><span style="color: #F6F6F4">: </span><span style="color: #97E1F1; font-style: italic">View </span><span style="color: #F6F6F4">{</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">@ObservedObject</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> diskInfoFetcher: DiskInfoFetcher</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body: </span><span style="color: #F286C4">some</span><span style="color: #F6F6F4"> View {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #97E1F1">Chart</span><span style="color: #F6F6F4">(diskInfoFetcher.diskInfos) { info </span><span style="color: #F286C4">in</span></span>
<span class="line"><span style="color: #F6F6F4">            </span><span style="color: #97E1F1">SectorMark</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">angle</span><span style="color: #F6F6F4">: .</span><span style="color: #BF9EEE">value</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">verbatim</span><span style="color: #F6F6F4">: info.title),</span></span>
<span class="line"><span style="color: #F6F6F4">                    info.percentage</span></span>
<span class="line"><span style="color: #F6F6F4">                ),</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">innerRadius</span><span style="color: #F6F6F4">: .</span><span style="color: #97E1F1">ratio</span><span style="color: #F6F6F4">(</span><span style="color: #BF9EEE">0.6</span><span style="color: #F6F6F4">),</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">angularInset</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">1.0</span></span>
<span class="line"><span style="color: #F6F6F4">            )</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">foregroundStyle</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #97E1F1">by</span><span style="color: #F6F6F4">: .</span><span style="color: #BF9EEE">value</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">verbatim</span><span style="color: #F6F6F4">: info.title),</span></span>
<span class="line"><span style="color: #F6F6F4">                    info.title</span></span>
<span class="line"><span style="color: #F6F6F4">                )</span></span>
<span class="line"><span style="color: #F6F6F4">            )</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">cornerRadius</span><span style="color: #F6F6F4">(</span><span style="color: #BF9EEE">3</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">            .</span><span style="color: #97E1F1">annotation</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">position</span><span style="color: #F6F6F4">: .overlay) {</span></span>
<span class="line"><span style="color: #F6F6F4">                </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> info.title </span><span style="color: #F286C4">!=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">System</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">                    </span><span style="color: #97E1F1">Text</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">(info.percentage * 100, specifier: </span><span style="color: #DEE492">&quot;</span><span style="color: #F286C4">%</span><span style="color: #F6F6F4">.</span><span style="color: #EE6666; font-style: italic; text-decoration: underline">1f</span><span style="color: #F286C4">%%</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">                        .</span><span style="color: #97E1F1">bold</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">                }</span></span>
<span class="line"><span style="color: #F6F6F4">            }</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">chartLegend</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">position</span><span style="color: #F6F6F4">: .trailing, </span><span style="color: #97E1F1">alignment</span><span style="color: #F6F6F4">: .center)</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">frame</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">height</span><span style="color: #F6F6F4">: </span><span style="color: #BF9EEE">120</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">padding</span><span style="color: #F6F6F4">(.trailing, </span><span style="color: #BF9EEE">70</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">        .</span><span style="color: #97E1F1">frame</span><span style="color: #F6F6F4">(</span><span style="color: #97E1F1">maxWidth</span><span style="color: #F6F6F4">: .</span><span style="color: #BF9EEE">infinity</span><span style="color: #F6F6F4">, </span><span style="color: #97E1F1">alignment</span><span style="color: #F6F6F4">: .center)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:27px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="gb-block-image gb-block-image-18f7977a"><img loading="lazy" decoding="async" width="892" height="846" class="gb-image gb-image-18f7977a" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_finished.webp" alt="" title="diskanalyser_app_finished" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_finished.webp 892w, https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_finished-300x285.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2025/02/diskanalyser_app_finished-768x728.webp 768w" sizes="auto, (max-width: 892px) 100vw, 892px" /></figure>



<p class="wp-block-paragraph">This view uses the Swift Charts framework (introduced in macOS 13) to create a donut chart of disk usage. Each sector represents a category, with its size proportional to the percentage of disk space it occupies. I&#8217;m adding percentage annotations to make the chart more informative.</p>



<div style="height:48px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Putting It All Together</h2>



<p class="wp-block-paragraph">With all these components in place, our app now provides a clean, informative interface for viewing disk usage. When a user clicks the menu bar icon, they see a window with:</p>



<ol class="wp-block-list">
<li>A title</li>



<li>A list of disk usage categories with progress bars</li>



<li>A donut chart visualizing the same information</li>
</ol>



<p class="wp-block-paragraph">The app demonstrates several important concepts for macOS utility development:</p>



<ul class="wp-block-list">
<li>Using menu bar extras for non-intrusive utilities</li>



<li>Executing and parsing command line tools</li>



<li>Presenting system information in a user-friendly way</li>



<li>Handling loading states and errors</li>



<li>Using modern SwiftUI features like Charts</li>
</ul>



<div style="height:39px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Platform-Specific Considerations</h2>



<p class="wp-block-paragraph">When building macOS utilities that use command line tools, there are a few important considerations:</p>



<ol class="wp-block-list">
<li><p><strong>Sandbox Limitations</strong>: If you plan to distribute your app through the Mac App Store, be aware that sandboxed apps have limited access to command line tools and system information. You may need to request specific entitlements or consider alternative distribution methods.</p></li>



<li><p><strong>Command Line Tool Changes</strong>: The output format of command line tools can change between macOS versions. Make your parsing code robust and consider adding version checks for critical differences.</p></li>



<li><p><strong>Performance</strong>: Running command line tools isn&#8217;t free &#8211; it spawns new processes and can be relatively slow. Consider caching results and limiting how often you refresh data.</p></li>



<li><p><strong>Privacy</strong>: Modern macOS versions are increasingly privacy-focused. If your app needs access to sensitive system information, be prepared to request appropriate permissions and explain why you need them.</p></li>
</ol>



<div style="height:26px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph"><a href="https://school.swiftyplace.com/f/macos-utilty-project-funnel" target="_blank" rel="noreferrer noopener"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2b07.png" alt="⬇" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong> Download project files</strong></a></p>



<div style="height:38px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">Building macOS utility apps that leverage command line tools gives you access to powerful system capabilities while still providing users with a friendly, modern interface. In this tutorial, we&#8217;ve built a disk analyzer that:</p>



<ul class="wp-block-list">
<li>Lives in the menu bar for easy access</li>



<li>Uses the <code>df</code> command to gather disk usage information</li>



<li>Presents that information in both textual and graphical formats</li>



<li>Handles loading states and errors gracefully</li>
</ul>



<p class="wp-block-paragraph">This pattern can be extended to many other types of utilities &#8211; network monitors, CPU usage trackers, file system watchers, and more. The combination of SwiftUI for the interface and command line tools for the functionality gives you the best of both worlds.</p>



<p class="wp-block-paragraph">I hope this tutorial has given you a solid foundation for building your own macOS utility apps. The ability to access system information through command line tools while presenting it in a beautiful SwiftUI interface opens up countless possibilities for helpful utilities that enhance the macOS experience.</p>



<p class="wp-block-paragraph">Happy coding!</p>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/building-macos-utiltiy-apps">Building macOS Utility Apps with Command Line Tools</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.swiftyplace.com/blog/building-macos-utiltiy-apps/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>NSAttributedString: Formatting Rich Text in Swift</title>
		<link>https://www.swiftyplace.com/blog/nsattributedstring-swift?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nsattributedstring-swift</link>
					<comments>https://www.swiftyplace.com/blog/nsattributedstring-swift#respond</comments>
		
		<dc:creator><![CDATA[Karin Prater]]></dc:creator>
		<pubDate>Mon, 17 Feb 2025 09:37:17 +0000</pubDate>
				<category><![CDATA[iOS app development]]></category>
		<category><![CDATA[macOS Development]]></category>
		<category><![CDATA[Swift]]></category>
		<category><![CDATA[SwiftUI]]></category>
		<guid isPermaLink="false">https://www.swiftyplace.com/?p=1005328</guid>

					<description><![CDATA[<p>Are you looking to add some style to your text in Swift with attributed string? You want to highlight important words, add links, or create beautifully formatted text, then you will want to learn about ... <a title="NSAttributedString: Formatting Rich Text in Swift" class="read-more" href="https://www.swiftyplace.com/blog/nsattributedstring-swift" aria-label="More on NSAttributedString: Formatting Rich Text in Swift">Read more</a></p>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/nsattributedstring-swift">NSAttributedString: Formatting Rich Text in Swift</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Are you looking to add some style to your text in Swift with attributed string? You want to highlight important words, add links, or create beautifully formatted text, then you will want to learn about AttributedString and NSAttributedString. This goes beyonde<a href="https://www.swiftyplace.com/blog/swiftui-font-and-texts"> <strong>basic text styling with font in Swift.</strong></a></p>



<p class="wp-block-paragraph"><strong>NSAttributedString</strong> is a class part of the Foundation framework and has been around since the early days of iOS/macOS. It&#8217;s Objective-C based and while it&#8217;s very powerful, it can be a bit verbose to use. You&#8217;ll still find it in many APIs and it&#8217;s particularly useful when working with UIKit or AppKit.</p>



<p class="wp-block-paragraph"><strong>AttributedString</strong>, is a new struct introduced in iOS 15, is the modern Swift-native implementation. It&#8217;s more type-safe and easier to work with in Swift code. It is build to work especially with text views in SwiftUI. However, it is much more limited than NSAttributedString in terms of styling options.</p>



<p class="wp-block-paragraph">In this guide, I&#8217;ll focus primarily on NSAttributedString as it&#8217;s still widely used and supported across all iOS/macOS versions. Plus, understanding NSAttributedString will help you better appreciate the improvements made in the newer AttributedString.</p>



<div style="height:28px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Creating and Modifying NSAttributedString</h2>



<p class="wp-block-paragraph">At its core, NSAttributedString is a string that lets you attach attributes (like font, color, or styling) to specific ranges of text. Unlike regular strings that maintain the same formatting throughout, NSAttributedString allows you to create rich text with varying styles within a single string.</p>



<p class="wp-block-paragraph">Here&#8217;s a simple example that creates a string with a red foreground color and bold font:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let attributedString = NSAttributedString(
    string: &quot;Hello World&quot;,
    attributes: [
        .foregroundColor: UIColor.red,
        .font: UIFont.boldSystemFont(ofSize: 16)
    ]
)" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> attributedString </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSAttributedString</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">    string: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Hello World</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">    attributes: [</span></span>
<span class="line"><span style="color: #F6F6F4">        .foregroundColor: UIColor.red,</span></span>
<span class="line"><span style="color: #F6F6F4">        .font: UIFont.</span><span style="color: #62E884">boldSystemFont</span><span style="color: #F6F6F4">(ofSize: </span><span style="color: #BF9EEE">16</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    ]</span></span>
<span class="line"><span style="color: #F6F6F4">)</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">You pass the base string and a dictionary of attributes. The key value are the attribute names. In the above example, the key is <code>.font</code> and its value is <code>UIFont.boldSystemFont(ofSize: 16)</code>. You can add as many attributes as you want.</p>



<p class="wp-block-paragraph">You can see the rendered attributed string in comparison to the default body text:</p>



<figure class="gb-block-image gb-block-image-f0fb292a"><img loading="lazy" decoding="async" width="826" height="322" class="gb-image gb-image-f0fb292a" src="http://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedsting_simpl_1.webp" alt="NSAttributedString example in Swift" title="nsattributedsting_simpl_1" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedsting_simpl_1.webp 826w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedsting_simpl_1-300x117.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedsting_simpl_1-768x299.webp 768w" sizes="auto, (max-width: 826px) 100vw, 826px" /></figure>



<div style="height:44px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Adding Partial Styling</h3>



<p class="wp-block-paragraph">If you only want to change the styling of a subrange, you can use<br><strong>NSMutableAttributedString</strong>:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let mutableString = NSMutableAttributedString(string: &quot;This is an attributed string with multiple styles.&quot;,
                                              attributes: [.font: UIFont.systemFont(ofSize: 17)])" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> mutableString </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSMutableAttributedString</span><span style="color: #F6F6F4">(string: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">This is an attributed string with multiple styles.</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">                                              attributes: [.font: UIFont.</span><span style="color: #62E884">systemFont</span><span style="color: #F6F6F4">(ofSize: </span><span style="color: #BF9EEE">17</span><span style="color: #F6F6F4">)])</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Then you can add attributes to a range of the string. The following makes the foreground color of the words &#8220;This is an&#8221; blue:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="mutableString.addAttribute(
    .foregroundColor,
    value: UIColor.blue,
    range: NSRange(location: 0, length: 11)
)" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F6F6F4">mutableString.</span><span style="color: #62E884">addAttribute</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">    .foregroundColor,</span></span>
<span class="line"><span style="color: #F6F6F4">    value: UIColor.blue,</span></span>
<span class="line"><span style="color: #F6F6F4">    range: </span><span style="color: #62E884">NSRange</span><span style="color: #F6F6F4">(location: </span><span style="color: #BF9EEE">0</span><span style="color: #F6F6F4">, length: </span><span style="color: #BF9EEE">11</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">)</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">You can get the range of a string like so:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let range = (mutableString.addAttribute as NSString).range(of: &quot;This is an&quot;)" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> range </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> (mutableString.addAttribute </span><span style="color: #F286C4">as</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">NSString</span><span style="color: #F6F6F4">).</span><span style="color: #62E884">range</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">of</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">This is an</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">This will give you a range that has a starting location <code>0</code> and a length of 11 for the 11 characters.</p>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="gb-block-image gb-block-image-cee00818"><img loading="lazy" decoding="async" width="783" height="115" class="gb-image gb-image-cee00818" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_2.webp" alt="" title="nsattributedstings_simple_2" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_2.webp 783w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_2-300x44.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_2-768x113.webp 768w" sizes="auto, (max-width: 783px) 100vw, 783px" /></figure>



<p class="wp-block-paragraph">You can add more addtional attributes for different parts of the string like so:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="attributedString.addAttribute(
    .font,
    value: UIFont.boldSystemFont(ofSize: 24),
    range: NSRange(location: 21, length: 21)
)" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F6F6F4">attributedString.</span><span style="color: #62E884">addAttribute</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">    .font,</span></span>
<span class="line"><span style="color: #F6F6F4">    value: UIFont.</span><span style="color: #62E884">boldSystemFont</span><span style="color: #F6F6F4">(ofSize: </span><span style="color: #BF9EEE">24</span><span style="color: #F6F6F4">),</span></span>
<span class="line"><span style="color: #F6F6F4">    range: </span><span style="color: #62E884">NSRange</span><span style="color: #F6F6F4">(location: </span><span style="color: #BF9EEE">21</span><span style="color: #F6F6F4">, length: </span><span style="color: #BF9EEE">21</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">)</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="gb-block-image gb-block-image-32a81401"><img loading="lazy" decoding="async" width="846" height="115" class="gb-image gb-image-32a81401" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedsting_simple_3-1.webp" alt="" title="nsattributedsting_simple_3" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedsting_simple_3-1.webp 846w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedsting_simple_3-1-300x41.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedsting_simple_3-1-768x104.webp 768w" sizes="auto, (max-width: 846px) 100vw, 846px" /></figure>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">If you add attributes to ranges that already have a previous value, the newly added attributes will overwrite the old one. For example below code will change the styling of &#8220;an&#8221; from blue to red:</p>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="attributedString.setAttributes([.foregroundColor : UIColor.red],
                               range: NSRange(location: 8, length: 20))" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F6F6F4">attributedString.</span><span style="color: #62E884">setAttributes</span><span style="color: #F6F6F4">([.foregroundColor : UIColor.red],</span></span>
<span class="line"><span style="color: #F6F6F4">                               range: </span><span style="color: #62E884">NSRange</span><span style="color: #F6F6F4">(location: </span><span style="color: #BF9EEE">8</span><span style="color: #F6F6F4">, length: </span><span style="color: #BF9EEE">20</span><span style="color: #F6F6F4">))</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="783" height="115" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedsting_simple_4.webp" alt="" class="wp-image-1005345" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedsting_simple_4.webp 783w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedsting_simple_4-300x44.webp 300w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedsting_simple_4-768x113.webp 768w" sizes="auto, (max-width: 783px) 100vw, 783px" /></figure>



<div style="height:64px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Basic Styling Attributes</h2>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">How to Change Color of NSAttribuedString</h3>



<p class="wp-block-paragraph">You can change the foreground and background color with the following attributes:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let text = NSMutableAttributedString(string: &quot;Styling Text in Swift&quot;)

// Adding color
text.addAttributes([
    .foregroundColor: UIColor.red
], range: NSRange(location: 8, length: 4))

// Adding background color
text.addAttributes([
    .backgroundColor: UIColor.yellow
], range: NSRange(location: 13, length: 5))" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> text </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSMutableAttributedString</span><span style="color: #F6F6F4">(string: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Styling Text in Swift</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #7B7F8B">// Adding color</span></span>
<span class="line"><span style="color: #F6F6F4">text.</span><span style="color: #62E884">addAttributes</span><span style="color: #F6F6F4">([</span></span>
<span class="line"><span style="color: #F6F6F4">    .foregroundColor: UIColor.red</span></span>
<span class="line"><span style="color: #F6F6F4">], range: </span><span style="color: #62E884">NSRange</span><span style="color: #F6F6F4">(location: </span><span style="color: #BF9EEE">8</span><span style="color: #F6F6F4">, length: </span><span style="color: #BF9EEE">4</span><span style="color: #F6F6F4">))</span></span>
<span class="line"></span>
<span class="line"><span style="color: #7B7F8B">// Adding background color</span></span>
<span class="line"><span style="color: #F6F6F4">text.</span><span style="color: #62E884">addAttributes</span><span style="color: #F6F6F4">([</span></span>
<span class="line"><span style="color: #F6F6F4">    .backgroundColor: UIColor.yellow</span></span>
<span class="line"><span style="color: #F6F6F4">], range: </span><span style="color: #62E884">NSRange</span><span style="color: #F6F6F4">(location: </span><span style="color: #BF9EEE">13</span><span style="color: #F6F6F4">, length: </span><span style="color: #BF9EEE">5</span><span style="color: #F6F6F4">))</span></span></code></pre></div>



<div style="height:42px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">How to Change the Font of NSAttribuedString</h3>



<p class="wp-block-paragraph">Here&#8217;s how to apply common text attributes, like font size, weight and traits:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let heavyFontPart = NSAttributedString(
    string: &quot;heavy font&quot;,
    attributes: [
        .font: UIFont.systemFont(ofSize: 20, weight: .heavy)
    ]
)

let boldfontPart = NSAttributedString(
    string: &quot;bold font&quot;,
    attributes: [
        .font: UIFont.boldSystemFont(ofSize: 20)
    ]
)

let italicFontPart = NSAttributedString(
    string: &quot;italic font&quot;,
    attributes: [
        .font: UIFont.italicSystemFont(ofSize: 20)
    ]
)" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> heavyFontPart </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSAttributedString</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">    string: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">heavy font</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">    attributes: [</span></span>
<span class="line"><span style="color: #F6F6F4">        .font: UIFont.</span><span style="color: #62E884">systemFont</span><span style="color: #F6F6F4">(ofSize: </span><span style="color: #BF9EEE">20</span><span style="color: #F6F6F4">, weight: .heavy)</span></span>
<span class="line"><span style="color: #F6F6F4">    ]</span></span>
<span class="line"><span style="color: #F6F6F4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> boldfontPart </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSAttributedString</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">    string: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">bold font</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">    attributes: [</span></span>
<span class="line"><span style="color: #F6F6F4">        .font: UIFont.</span><span style="color: #62E884">boldSystemFont</span><span style="color: #F6F6F4">(ofSize: </span><span style="color: #BF9EEE">20</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    ]</span></span>
<span class="line"><span style="color: #F6F6F4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> italicFontPart </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSAttributedString</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">    string: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">italic font</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">    attributes: [</span></span>
<span class="line"><span style="color: #F6F6F4">        .font: UIFont.</span><span style="color: #62E884">italicSystemFont</span><span style="color: #F6F6F4">(ofSize: </span><span style="color: #BF9EEE">20</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    ]</span></span>
<span class="line"><span style="color: #F6F6F4">)</span></span></code></pre></div>



<div style="height:15px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="gb-block-image gb-block-image-9127605d"><img loading="lazy" decoding="async" width="245" height="133" class="gb-image gb-image-9127605d" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_6_font.webp" alt="" title="nsattributedstings_simple_6_font"/></figure>



<div style="height:39px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">StrikeThrough and Underline Text</h3>



<p class="wp-block-paragraph">You can add attributes for strikethourgh and underline styles, where you can chose between single, double, and thick:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let strikeThroughPart = NSAttributedString(
    string: &quot;strike through text&quot;,
    attributes: [
        .strikethroughStyle: NSUnderlineStyle.single.rawValue,
        .strikethroughColor: UIColor.blue
    ]
)

let underlinePart = NSAttributedString(
    string: &quot;underline text&quot;,
    attributes: [
        .underlineStyle: NSUnderlineStyle.single.rawValue,
        .underlineColor: UIColor.red,
    ]
)" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> strikeThroughPart </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSAttributedString</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">    string: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">strike through text</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">    attributes: [</span></span>
<span class="line"><span style="color: #F6F6F4">        .strikethroughStyle: NSUnderlineStyle.single.rawValue,</span></span>
<span class="line"><span style="color: #F6F6F4">        .strikethroughColor: UIColor.blue</span></span>
<span class="line"><span style="color: #F6F6F4">    ]</span></span>
<span class="line"><span style="color: #F6F6F4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> underlinePart </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSAttributedString</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">    string: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">underline text</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">    attributes: [</span></span>
<span class="line"><span style="color: #F6F6F4">        .underlineStyle: NSUnderlineStyle.single.rawValue,</span></span>
<span class="line"><span style="color: #F6F6F4">        .underlineColor: UIColor.red,</span></span>
<span class="line"><span style="color: #F6F6F4">    ]</span></span>
<span class="line"><span style="color: #F6F6F4">)</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="gb-block-image gb-block-image-c565ce4a"><img loading="lazy" decoding="async" width="321" height="96" class="gb-image gb-image-c565ce4a" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_7_underline_color.webp" alt="" title="nsattributedstings_simple_7_underline_color" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_7_underline_color.webp 321w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_7_underline_color-300x90.webp 300w" sizes="auto, (max-width: 321px) 100vw, 321px" /></figure>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Adding Clickable Links and Paragraph Styles</h3>



<p class="wp-block-paragraph">You can add a link to a substring with the link attributes. The value should either be a NSURL or String tpye. In the following example, I linked to the Apple website:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let linkText = NSMutableAttributedString(string: &quot;Visit Apple's website&quot;)

// Adding a link
let linkRange = NSRange(location: 6, length: 6)
linkText.addAttribute(.link, 
                      value: &quot;https://www.apple.com&quot;, 
                      range: linkRange)" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> linkText </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSMutableAttributedString</span><span style="color: #F6F6F4">(string: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Visit Apple&#39;s website</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #7B7F8B">// Adding a link</span></span>
<span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> linkRange </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSRange</span><span style="color: #F6F6F4">(location: </span><span style="color: #BF9EEE">6</span><span style="color: #F6F6F4">, length: </span><span style="color: #BF9EEE">6</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">linkText.</span><span style="color: #62E884">addAttribute</span><span style="color: #F6F6F4">(.link, </span></span>
<span class="line"><span style="color: #F6F6F4">                      value: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">https://www.apple.com</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">, </span></span>
<span class="line"><span style="color: #F6F6F4">                      range: linkRange)</span></span></code></pre></div>



<div style="height:19px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="gb-block-image gb-block-image-ba588fa1"><img loading="lazy" decoding="async" width="321" height="46" class="gb-image gb-image-ba588fa1" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_8_link.webp" alt="" title="nsattributedstings_simple_8_link" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_8_link.webp 321w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_8_link-300x43.webp 300w" sizes="auto, (max-width: 321px) 100vw, 321px" /></figure>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Note that the rendered styling is defined by the view where this is used. Even if you set a differnt foreground color, the styling will be internally handled be the view e.g. UITextView/NSTextView.</p>



<div style="height:34px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Text Alignment and Spacing with Paragraph Styles</h3>



<p class="wp-block-paragraph">Styling for text alignment and spacing is handled with paragraph styles. The following creates a styling with center alignmed text and a line spacing of 10:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let style = NSMutableParagraphStyle()
style.alignment = .center
style.lineSpacing = 10" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> style </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSMutableParagraphStyle</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">style.alignment </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .center</span></span>
<span class="line"><span style="color: #F6F6F4">style.lineSpacing </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">10</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">You add this style to the attributes dictionary of NSAttributedString:</p>



<p class="wp-block-paragraph">You can create customize paragraph formatting:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let firstParagraphAttributes: [NSAttributedString.Key : Any] = [.paragraphStyle: style,
                                                                .font: UIFont.systemFont(ofSize: 17),
                                                                .foregroundColor: UIColor.blue]

let firstParagraphText = &quot;&quot;&quot;
First Paragraph
This paragraph demonstrates center alignment with increased line spacing.
&quot;&quot;&quot;

let firstParagraph = NSAttributedString(string: firstParagraphText,
                                       attributes: firstParagraphAttributes)" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> firstParagraphAttributes</span><span style="color: #F286C4">:</span><span style="color: #F6F6F4"> [</span><span style="color: #97E1F1; font-style: italic">NSAttributedString</span><span style="color: #F6F6F4">.</span><span style="color: #97E1F1; font-style: italic">Key</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">:</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">Any</span><span style="color: #F6F6F4">] </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> [.paragraphStyle: style,</span></span>
<span class="line"><span style="color: #F6F6F4">                                                                .font: UIFont.</span><span style="color: #62E884">systemFont</span><span style="color: #F6F6F4">(ofSize: </span><span style="color: #BF9EEE">17</span><span style="color: #F6F6F4">),</span></span>
<span class="line"><span style="color: #F6F6F4">                                                                .foregroundColor: UIColor.blue]</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> firstParagraphText </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #DEE492">&quot;&quot;&quot;</span></span>
<span class="line"><span style="color: #E7EE98">First Paragrap</span><span style="color: #EE6666; font-style: italic; text-decoration: underline">h</span></span>
<span class="line"><span style="color: #F6F6F4">This paragraph demonstrates center alignment </span><span style="color: #F286C4">with</span><span style="color: #F6F6F4"> increased line spacing.</span></span>
<span class="line"><span style="color: #DEE492">&quot;&quot;&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E7EE98">let firstParagraph = NSAttributedString(string: firstParagraphText</span><span style="color: #EE6666; font-style: italic; text-decoration: underline">,</span></span>
<span class="line"><span style="color: #F6F6F4">                                       attributes: firstParagraphAttributes)</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="gb-block-image gb-block-image-0fa5367e"><img loading="lazy" decoding="async" width="586" height="308" class="gb-image gb-image-0fa5367e" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_9_paragrph.webp" alt="" title="nsattributedstings_simple_9_paragrph" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_9_paragrph.webp 586w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_9_paragrph-300x158.webp 300w" sizes="auto, (max-width: 586px) 100vw, 586px" /></figure>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Other parameters that you can change per paragraph are:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="style.firstLineHeadIndent = 40  // Indent first line
style.headIndent = 20           // Indent other lines

style.minimumLineHeight = 25
style.maximumLineHeight = 30

style.lineSpacing = 10
style.paragraphSpacing = 20     // Space after paragraph
style.paragraphSpacingBefore = 10  // Space before paragraph" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F6F6F4">style.firstLineHeadIndent </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">40</span><span style="color: #F6F6F4">  </span><span style="color: #7B7F8B">// Indent first line</span></span>
<span class="line"><span style="color: #F6F6F4">style.headIndent </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">20</span><span style="color: #F6F6F4">           </span><span style="color: #7B7F8B">// Indent other lines</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">style.minimumLineHeight </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">25</span></span>
<span class="line"><span style="color: #F6F6F4">style.maximumLineHeight </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">30</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">style.lineSpacing </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">10</span></span>
<span class="line"><span style="color: #F6F6F4">style.paragraphSpacing </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">20</span><span style="color: #F6F6F4">     </span><span style="color: #7B7F8B">// Space after paragraph</span></span>
<span class="line"><span style="color: #F6F6F4">style.paragraphSpacingBefore </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #BF9EEE">10</span><span style="color: #F6F6F4">  </span><span style="color: #7B7F8B">// Space before paragraph</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">You can also work with paragraph styles if you want to create lists:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let paragraphStyle = NSMutableParagraphStyle()
let textList = NSTextList(markerFormat: .disc, options: 1) // Bullet format
paragraphStyle.textLists = [textList]" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> paragraphStyle </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSMutableParagraphStyle</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> textList </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSTextList</span><span style="color: #F6F6F4">(markerFormat: .disc, options: </span><span style="color: #BF9EEE">1</span><span style="color: #F6F6F4">) </span><span style="color: #7B7F8B">// Bullet format</span></span>
<span class="line"><span style="color: #F6F6F4">paragraphStyle.textLists </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> [textList]</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="gb-block-image gb-block-image-8f96c1da"><img loading="lazy" decoding="async" width="586" height="308" class="gb-image gb-image-8f96c1da" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_10_paragrph_list.webp" alt="" title="nsattributedstings_simple_10_paragrph_list" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_10_paragrph_list.webp 586w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_10_paragrph_list-300x158.webp 300w" sizes="auto, (max-width: 586px) 100vw, 586px" /></figure>



<div style="height:47px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Adding Images and Attachments</h3>



<p class="wp-block-paragraph">Here&#8217;s something cool &#8211; you can even embed images in your attributed strings! This is perfect for creating rich content:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let attachment = NSTextAttachment()
attachment.image = UIImage(systemName: &quot;star.fill&quot;)
attachment.bounds = CGRect(x: 0, y: -5, width: 20, height: 20)

let imageString = NSAttributedString(attachment: attachment)
let textString = NSAttributedString(string: &quot; Rating: 4.5/5&quot;)

let combination = NSMutableAttributedString()
combination.append(imageString)
combination.append(textString)

return combination" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> attachment </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSTextAttachment</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">attachment.image </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">UIImage</span><span style="color: #F6F6F4">(systemName: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">star.fill</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">attachment.bounds </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">CGRect</span><span style="color: #F6F6F4">(x: </span><span style="color: #BF9EEE">0</span><span style="color: #F6F6F4">, y: </span><span style="color: #F286C4">-</span><span style="color: #BF9EEE">5</span><span style="color: #F6F6F4">, width: </span><span style="color: #BF9EEE">20</span><span style="color: #F6F6F4">, height: </span><span style="color: #BF9EEE">20</span><span style="color: #F6F6F4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> imageString </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSAttributedString</span><span style="color: #F6F6F4">(attachment: attachment)</span></span>
<span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> textString </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSAttributedString</span><span style="color: #F6F6F4">(string: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98"> Rating: 4.5/5</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> combination </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSMutableAttributedString</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F6F6F4">combination.</span><span style="color: #62E884">append</span><span style="color: #F6F6F4">(imageString)</span></span>
<span class="line"><span style="color: #F6F6F4">combination.</span><span style="color: #62E884">append</span><span style="color: #F6F6F4">(textString)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F286C4">return</span><span style="color: #F6F6F4"> combination</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph"><strong>Pro tip:</strong> When working with text attachments, pay attention to the bounds property. The y value can be used to adjust the vertical alignment of your image relative to the text baseline.</p>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Using NSAttributedString with SwiftUI and UIKit</h2>



<p class="wp-block-paragraph">When it comes to implementing NSAttributedString in your iOS apps, you have different approaches depending on whether you&#8217;re using UIKit or SwiftUI. Let me show you how to handle both frameworks effectively.</p>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Using NSAttributedString with UIKit</h3>



<p class="wp-block-paragraph">In UIKit, several UI components directly support NSAttributedString through their <code>attributedText</code> property. Here&#8217;s how you can use it with <strong>UILabel</strong>:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="// Using with UILabel
let label = UILabel()
let attributedText = NSAttributedString(
    string: &quot;Hello World&quot;,
    attributes: [
        .foregroundColor: UIColor.blue,
        .font: UIFont.boldSystemFont(ofSize: 20)
    ]
)
label.attributedText = attributedText" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #7B7F8B">// Using with UILabel</span></span>
<span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> label </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">UILabel</span><span style="color: #F6F6F4">()</span></span>
<span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> attributedText </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSAttributedString</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">    string: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Hello World</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">,</span></span>
<span class="line"><span style="color: #F6F6F4">    attributes: [</span></span>
<span class="line"><span style="color: #F6F6F4">        .foregroundColor: UIColor.blue,</span></span>
<span class="line"><span style="color: #F6F6F4">        .font: UIFont.</span><span style="color: #62E884">boldSystemFont</span><span style="color: #F6F6F4">(ofSize: </span><span style="color: #BF9EEE">20</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    ]</span></span>
<span class="line"><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">label.attributedText </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> attributedText</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">You can also set an attributed string to UITextView</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="// Using with UITextView
let textView = UITextView() // wil use Textkit 2 per defaul
textView.attributedText = attributedText" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #7B7F8B">// Using with UITextView</span></span>
<span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> textView </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">UITextView</span><span style="color: #F6F6F4">() </span><span style="color: #7B7F8B">// wil use Textkit 2 per defaul</span></span>
<span class="line"><span style="color: #F6F6F4">textView.attributedText </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> attributedText</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>


<div class="gb-container gb-container-a85245d8">
<div class="gb-container gb-container-4359b553">

<p class="wp-block-paragraph">The actual rendering is done by the view which might ignore certain attributes. It might also be different for <strong><a href="https://developer.apple.com/documentation/uikit/using-textkit-2-to-interact-with-text" target="_blank" rel="noopener">TextKit 1 or 2</a> </strong>and if you are on macOS or iOS. </p>

</div>
</div>


<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Attributed String in SwiftUI</h3>



<p class="wp-block-paragraph">SwiftUI introduced its own <code>AttributedString</code> type in iOS 15, which is more Swift-friendly than NSAttributedString. Here is a simple example in SwiftUI:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="struct ContentView: View {
    var body: some View {
        Text(makeAttributedString())
    }

    func makeAttributedString() -&gt; AttributedString {
        var attributedString = AttributedString(&quot;Hello World&quot;)
        attributedString.foregroundColor = .blue
        attributedString.font = .system(.title, design: .rounded)

        if let range = attributedString.range(of: &quot;World&quot;) {
             attributedString[range].backgroundColor = .green
        }
        return attributedString
    }
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F6F6F4">struct ContentView: View {</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> body</span><span style="color: #F286C4">:</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">some</span><span style="color: #F6F6F4"> </span><span style="color: #97E1F1; font-style: italic">View</span><span style="color: #F6F6F4"> {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #62E884">Text</span><span style="color: #F6F6F4">(</span><span style="color: #62E884">makeAttributedString</span><span style="color: #F6F6F4">())</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    func </span><span style="color: #62E884">makeAttributedString</span><span style="color: #F6F6F4">() </span><span style="color: #F286C4">-&gt;</span><span style="color: #F6F6F4"> AttributedString {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">var</span><span style="color: #F6F6F4"> attributedString </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">AttributedString</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Hello World</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">        attributedString.foregroundColor </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .blue</span></span>
<span class="line"><span style="color: #F6F6F4">        attributedString.font </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> .</span><span style="color: #62E884">system</span><span style="color: #F6F6F4">(.title, design: .rounded)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> range </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> attributedString.</span><span style="color: #62E884">range</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">of</span><span style="color: #F6F6F4">: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">World</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">) {</span></span>
<span class="line"><span style="color: #F6F6F4">             attributedString[range].backgroundColor = .green</span></span>
<span class="line"><span style="color: #F6F6F4">        }</span></span>
<span class="line"><span style="color: #F6F6F4">        return attributedString</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">AttributedString is very limited. For example header styles are not supported. and only supports the following stylings:</p>



<ul class="wp-block-list">
<li>font (including bold and italic)</li>



<li>foregroundcolor</li>



<li>backgroundColor</li>



<li>strikethroughStyle</li>



<li>underlineStyle</li>
</ul>



<p class="wp-block-paragraph">You can also use <strong>markdown</strong> with AttributedString. But the markdown support is very basic and limited to the following:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let thankYouString = try AttributedString(markdown:&quot;This is a **bold** and *italic* and `code` with ~~strikethrough~~. [click this link](https://www.apple.com)&quot;)" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> thankYouString </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> try </span><span style="color: #62E884">AttributedString</span><span style="color: #F6F6F4">(markdown:</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">This is a **bold** and *italic* and `code` with ~~strikethrough~~. [click this link](https://www.apple.com)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="gb-block-image gb-block-image-b3a1cf6d"><img loading="lazy" decoding="async" width="736" height="66" class="gb-image gb-image-b3a1cf6d" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_11_swiftui_markdown.webp" alt="" title="nsattributedstings_simple_11_swiftui_markdown" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_11_swiftui_markdown.webp 736w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_11_swiftui_markdown-300x27.webp 300w" sizes="auto, (max-width: 736px) 100vw, 736px" /></figure>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Converting Between AttributedString and NSAttributedString</h3>



<p class="wp-block-paragraph">Sometimes you need to convert between SwiftUI&#8217;s AttributedString and NSAttributedString:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="// Converting NSAttributedString to AttributedString
NSAttributedString(attributedString: attributedString)" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #7B7F8B">// Converting NSAttributedString to AttributedString</span></span>
<span class="line"><span style="color: #62E884">NSAttributedString</span><span style="color: #F6F6F4">(attributedString: attributedString)</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">Note that SwiftUI does not render all attributes. For example, NSList or NSTable will not be shown.</p>



<div style="height:41px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Getting Attributes from NSAttributedString</h2>



<p class="wp-block-paragraph">When working with NSAttributedString, you&#8217;ll often need to read and analyze the attributes applied to different parts of the text. Let me show you how to effectively retrieve these attributes in your Swift code.</p>



<p class="wp-block-paragraph">I will use the following as an example:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let attributedString = NSMutableAttributedString(string: &quot;A text with a background color.&quot;)

// Applying foreground color to &quot;text&quot;
attributedString.addAttributes(
    [.foregroundColor : UIColor.red],
    range: NSRange(location: 2, length: 4)
)

// Applying background color to &quot;text with a background&quot;
attributedString.addAttributes(
    [.backgroundColor: UIColor.yellow],
    range: NSRange(location: 2, length: 22)
)" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> attributedString </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSMutableAttributedString</span><span style="color: #F6F6F4">(string: </span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">A text with a background color.</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #7B7F8B">// Applying foreground color to &quot;text&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">attributedString.</span><span style="color: #62E884">addAttributes</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">    [.foregroundColor : UIColor.red],</span></span>
<span class="line"><span style="color: #F6F6F4">    range: </span><span style="color: #62E884">NSRange</span><span style="color: #F6F6F4">(location: </span><span style="color: #BF9EEE">2</span><span style="color: #F6F6F4">, length: </span><span style="color: #BF9EEE">4</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #7B7F8B">// Applying background color to &quot;text with a background&quot;</span></span>
<span class="line"><span style="color: #F6F6F4">attributedString.</span><span style="color: #62E884">addAttributes</span><span style="color: #F6F6F4">(</span></span>
<span class="line"><span style="color: #F6F6F4">    [.backgroundColor: UIColor.yellow],</span></span>
<span class="line"><span style="color: #F6F6F4">    range: </span><span style="color: #62E884">NSRange</span><span style="color: #F6F6F4">(location: </span><span style="color: #BF9EEE">2</span><span style="color: #F6F6F4">, length: </span><span style="color: #BF9EEE">22</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">)</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="gb-block-image gb-block-image-d70eccf9"><img loading="lazy" decoding="async" width="503" height="66" class="gb-image gb-image-d70eccf9" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_12_testing.webp" alt="" title="nsattributedstings_simple_12_testing" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_12_testing.webp 503w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_12_testing-300x39.webp 300w" sizes="auto, (max-width: 503px) 100vw, 503px" /></figure>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Basic Attribute Retrieval</h3>



<p class="wp-block-paragraph">The simplest way to get attributes is using the attributes(at:effectiveRange:) method:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="// Get attributes at a specific location
if let attributes = attributedString.attributes(at: 3, effectiveRange: nil) {
    if let color = attributes[.foregroundColor] as? UIColor {
        print(&quot;Text color at position 3 is: (color)&quot;)
    }
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #7B7F8B">// Get attributes at a specific location</span></span>
<span class="line"><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> attributes </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> attributedString.</span><span style="color: #62E884">attributes</span><span style="color: #F6F6F4">(at: </span><span style="color: #BF9EEE">3</span><span style="color: #F6F6F4">, effectiveRange: nil) {</span></span>
<span class="line"><span style="color: #F6F6F4">    if let color </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> attributes[.foregroundColor] as</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> UIColor {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #62E884">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Text color at position 3 is: (color)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Enumerating Single Attributes</h3>



<p class="wp-block-paragraph">If you&#8217;re interested in finding all occurrences of a specific attribute (like background color), you can use enumerateAttribute:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let fullRange = NSRange(location: 0, length: attributedString.length)

  //Enumerate .backgroundColor to detect highlighted text.
attributedString.enumerateAttribute(.backgroundColor, in: fullRange, options: []) { value, range, _ in
    if let color = value as? NSColor {
       let text = attributedString.attributedSubstring(from: range)
       print(&quot;found a background color for text: (text)&quot;)
    }
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> fullRange </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSRange</span><span style="color: #F6F6F4">(location: </span><span style="color: #BF9EEE">0</span><span style="color: #F6F6F4">, length: attributedString.length)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">  </span><span style="color: #7B7F8B">//Enumerate .backgroundColor to detect highlighted text.</span></span>
<span class="line"><span style="color: #F6F6F4">attributedString.</span><span style="color: #62E884">enumerateAttribute</span><span style="color: #F6F6F4">(.backgroundColor, </span><span style="color: #F286C4">in</span><span style="color: #F6F6F4">: fullRange, options: []) { value, range, _ </span><span style="color: #F286C4">in</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> color </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> value as</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> NSColor {</span></span>
<span class="line"><span style="color: #F6F6F4">       let text </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> attributedString.</span><span style="color: #62E884">attributedSubstring</span><span style="color: #F6F6F4">(from: range)</span></span>
<span class="line"><span style="color: #F6F6F4">       </span><span style="color: #62E884">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">found a background color for text: (text)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The closure will be called 3 times, where the second time the range for the yellow background color is given.</p>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">Enumerating All Attributes</h3>



<p class="wp-block-paragraph">To examine all attributes in a string, use enumerateAttributes:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono-NL.ttf" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono-NL,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#f6f6f4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="let fullRange = NSRange(location: 0, length: attributedString.length)

attributedString.enumerateAttributes(in: fullRange) { attributes, range, _ in
    // Check for background color
    if let backgroundColor = attributes[.backgroundColor] as? UIColor {
        print(&quot;Range (range) has background color: (backgroundColor)&quot;)
    }

    // Check for text color
    if let textColor = attributes[.foregroundColor] as? UIColor {
        print(&quot;Range (range) has text color: (textColor)&quot;)
    }

    // Check for font
    if let font = attributes[.font] as? UIFont {
        print(&quot;Range (range) uses font: (font)&quot;)
    }
}" style="color:#f6f6f4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M16.5 8.25V6a2.25 2.25 0 00-2.25-2.25H6A2.25 2.25 0 003.75 6v8.25A2.25 2.25 0 006 16.5h2.25m8.25-8.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-7.5A2.25 2.25 0 018.25 18v-1.5m8.25-8.25h-6a2.25 2.25 0 00-2.25 2.25v6"></path></svg></span><pre class="shiki dracula-soft" style="background-color: #282A36" tabindex="0"><code><span class="line"><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> fullRange </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> </span><span style="color: #62E884">NSRange</span><span style="color: #F6F6F4">(location: </span><span style="color: #BF9EEE">0</span><span style="color: #F6F6F4">, length: attributedString.length)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">attributedString.</span><span style="color: #62E884">enumerateAttributes</span><span style="color: #F6F6F4">(</span><span style="color: #F286C4">in</span><span style="color: #F6F6F4">: fullRange) { attributes, range, _ </span><span style="color: #F286C4">in</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// Check for background color</span></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #F286C4">if</span><span style="color: #F6F6F4"> </span><span style="color: #F286C4">let</span><span style="color: #F6F6F4"> backgroundColor </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> attributes[.backgroundColor] as</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> UIColor {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #62E884">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Range (range) has background color: (backgroundColor)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// Check for text color</span></span>
<span class="line"><span style="color: #F6F6F4">    if let textColor </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> attributes[.foregroundColor] as</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> UIColor {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #62E884">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Range (range) has text color: (textColor)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color: #F6F6F4">    </span><span style="color: #7B7F8B">// Check for font</span></span>
<span class="line"><span style="color: #F6F6F4">    if let font </span><span style="color: #F286C4">=</span><span style="color: #F6F6F4"> attributes[.font] as</span><span style="color: #F286C4">?</span><span style="color: #F6F6F4"> UIFont {</span></span>
<span class="line"><span style="color: #F6F6F4">        </span><span style="color: #62E884">print</span><span style="color: #F6F6F4">(</span><span style="color: #DEE492">&quot;</span><span style="color: #E7EE98">Range (range) uses font: (font)</span><span style="color: #DEE492">&quot;</span><span style="color: #F6F6F4">)</span></span>
<span class="line"><span style="color: #F6F6F4">    }</span></span>
<span class="line"><span style="color: #F6F6F4">}</span></span></code></pre></div>



<div style="height:14px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">The closure will be called for all range that have differnt attributes. For the above attributes you will get 4 ranges:</p>



<figure class="gb-block-image gb-block-image-90e3ac05"><img loading="lazy" decoding="async" width="503" height="66" class="gb-image gb-image-90e3ac05" src="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_12_testing_parts.webp" alt="" title="nsattributedstings_simple_12_testing_parts" srcset="https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_12_testing_parts.webp 503w, https://www.swiftyplace.com/wp-content/uploads/2025/02/nsattributedstings_simple_12_testing_parts-300x39.webp 300w" sizes="auto, (max-width: 503px) 100vw, 503px" /></figure>



<div style="height:34px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Performance Tips <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h2>



<ul class="wp-block-list">
<li>Cache attributed strings when possible</li>



<li>Use NSMutableAttributedString only when you need to modify the text</li>



<li>Consider using AttributedString for SwiftUI-only apps in iOS 15+</li>
</ul>



<div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">NSAttributedString is an essential tool for any iOS developer looking to create sophisticated text experiences in their apps. By mastering its capabilities, you can create more engaging and visually appealing applications that stand out in the App Store. Start implementing these concepts in your next project, and remember to consider both UIKit and SwiftUI approaches for maximum flexibility and compatibility.</p>



<p class="wp-block-paragraph"><strong>Further Reading:</strong></p>



<ul class="wp-block-list">
<li><a href="https://www.swiftyplace.com/blog/swiftui-font-and-texts">SwiftUI Font and Texts</a></li>



<li>Mastering SwiftUI Buttons:<a href="https://www.swiftyplace.com/blog/mastering-swiftui-buttons-a-comprehensive-guide-to-creating-and-customizing-buttons" target="_blank" rel="noopener"> A Comprehensive Guide to Creating and Customizing Buttons</a></li>



<li><a href="https://www.swiftyplace.com/blog/mastering-swiftui-image-view" target="_blank" rel="noopener">SwiftUI Image View </a></li>



<li><a href="https://www.swiftyplace.com/blog/swiftui-list-view-a-deep-dive-into-one-of-the-most-important-components-of-swiftui" target="_blank" rel="noopener">Deep Dive into SwiftUI List View</a></li>



<li><a href="https://www.swiftyplace.com/blog/nsattributedstring-swift">Rich Text Formating with NSAttributedString and AttributedString</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://www.swiftyplace.com/blog/nsattributedstring-swift">NSAttributedString: Formatting Rich Text in Swift</a> appeared first on <a rel="nofollow" href="https://www.swiftyplace.com">swiftyplace</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.swiftyplace.com/blog/nsattributedstring-swift/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: www.swiftyplace.com @ 2026-12-01 06:06:35 by W3 Total Cache
-->