<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mathis Gaignet on Medium]]></title>
        <description><![CDATA[Stories by Mathis Gaignet on Medium]]></description>
        <link>https://medium.com/@matgnt?source=rss-43a7c410e21a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EX3ySPZLsBIfmtfzeep3zA.jpeg</url>
            <title>Stories by Mathis Gaignet on Medium</title>
            <link>https://medium.com/@matgnt?source=rss-43a7c410e21a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 03:28:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matgnt/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Stop Using Task.detached!]]></title>
            <link>https://medium.com/@matgnt/stop-using-task-detached-d8e060ae51a5?source=rss-43a7c410e21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8e060ae51a5</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Mathis Gaignet]]></dc:creator>
            <pubDate>Thu, 04 Dec 2025 07:06:02 GMT</pubDate>
            <atom:updated>2025-12-05T16:21:49.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*deuuY2uoCWpGY2uGbR9-oQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@polarmermaid?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Anne Nygård</a> on <a href="https://unsplash.com/photos/silver-safety-pin-on-white-paper-Sl69Jw-o0rU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I’ve seen many developers misuse Task.detached, most often using it the same way they would use DispatchQueue.global.async() to run functions on the background thread pool. But this function is not meant for that at all, and the documentation is quite clear on this. Let’s dive into the inner workings of Task.detached together.</p><h4>What Is A Task?</h4><p>As you probably know, a Task (or unstructured Task) is a unit of asynchronous work that inherits the context from where it’s created. By context, I mean several things:</p><p>First, if the Task is declared from within a @globalActor like the @MainActor, it inherits its isolation and SerialExecutor thanks to an internal compiler attribute, @_InheritActorContext, on the Task initializer. (For instance actors, check out the comments of this post).</p><pre>struct ContentView: View {<br>    var body: some View {<br>        Button(&quot;Test MainActor inheritance&quot;) {<br>            Task {<br>                // Check the isolation<br>                // Result: Isolated to Optional(Swift.MainActor)<br>                print(&quot;Isolated to \(String(describing: #isolation))&quot;)<br><br>                // Should crash if the Task is not running on the MainActor Serial Executor<br>                // Result: It doesn&#39;t crash<br>                print(MainActor.assertIsolated())<br>            }<br>        }<br>    }<br>}</pre><p>It will also inherit the priority.</p><pre>struct ContentView: View {<br>    var body: some View {<br>        Button(&quot;Test Task priority&quot;) {<br>            Task {<br>                // Result: TaskPriority.high<br>                print(&quot;Task priority is \(Task.currentPriority)&quot;)<br>                Task(priority: .low) {<br>                    // Result: TaskPriority.low<br>                    print(&quot;Task priority is \(Task.currentPriority)&quot;)<br>                    Task {<br>                        // Result: TaskPriority.low<br>                        print(&quot;Task priority is \(Task.currentPriority)&quot;)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>And the @TaskLocal if you use it in your app:</p><pre>struct ContentView: View {<br>    @TaskLocal static var userID: String = &quot;anonymous&quot;<br><br>    var body: some View {<br>        VStack(spacing: 20) {<br>            Button(&quot;Test TaskLocal Inheritance&quot;) {<br>                testTaskLocalInheritance()<br>            }<br>        }<br>    }<br><br>    func testTaskLocalInheritance() {<br>        Self.$userID.withValue(&quot;user-123&quot;) {<br>            Task {<br>                print(&quot;Task {}: \(Self.userID)&quot;) // &quot;user-123&quot;<br>            }<br>        }<br>    }<br>}</pre><p>This information is available in the <a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/">documentation</a>:</p><blockquote>To create an unstructured task that runs similarly to the surrounding code, call the Task.init(name:priority:operation:) initializer. The new task defaults to running with the same actor isolation, priority, and task-local state <strong>as the current task</strong>.</blockquote><p>I highlighted <em>current task</em> because each of these three elements is <strong>inheritable</strong> from the Task in which it is created. In short, it’s possible to change the isolation for a Task, declare nested tasks in it, and all of these tasks will no longer inherit the ‘original’ actor. The same applies to priority, as you saw in the example, and it’s also true for @TaskLocal.</p><h4>What Is A Detached Task?</h4><p>Well, a Task.detached doesn’t inherit any of that. It will lose the isolation, the SerialExecutor of its current actor, its priority will reset to the default (medium), and it won’t have the value of the @TaskLocal.</p><p>Once again, it’s stated clearly in the documentation:</p><blockquote>To create an unstructured task that’s more independent from the surrounding code, known more specifically as a <strong>detached task</strong>, call the Task.detached(name:priority:operation:) static method. The new task defaults to running without any actor isolation and doesn’t inherit the current task’s priority or task-local state. Both of these operations return a task that you can interact with — for example, to wait for its result or to cancel it.</blockquote><p>Returning to my previous examples on the inheritance of the three properties, we can see that Task.detached is, as its name suggests, completely detached from this inheritance:</p><pre>struct ContentView: View {<br>    @TaskLocal static var userID: String = &quot;anonymous&quot;<br><br>    var body: some View {<br>        Button(&quot;Test Task priority&quot;) {<br>            detachedTaskExample()<br>        }<br>    }<br>    func detachedTaskExample() {<br>        Self.$userID.withValue(&quot;user-123&quot;) {<br>            Task(priority: .low) {<br>                // MainActor isolated<br>                // Priority low<br>                // user-123<br>                Task {<br>                    // MainActor isolated<br>                    // Priority low<br>                    // user-123<br>                    Task {<br>                        // MainActor isolated<br>                        // Priority low<br>                        // user-123<br>                        Task.detached {<br>                            // isolated to nil<br>                            // Priority medium<br>                            // anonymous<br>                            Task {<br>                                // isolated to nil<br>                                // Priority medium<br>                                // anonymous<br>                                Task {<br>                                    // isolated to nim<br>                                    // Priority medium<br>                                    // anonymous<br>                                }<br>                            }<br>                        }<br>                    }<br>                }<br>            }<br>            <br>        }<br>    }<br>}</pre><p><em>PS: Don’t confuse unstructured and structured concurrency. Structured concurrency uses </em><em>async let and </em><em>TaskGroup, and the code inside is called child tasks. A regular Task is unstructured. Although two nested Tasks inherit the three things mentioned above, they have nothing to do with the error propagation or cancellation that structured concurrency provides.</em></p><h4>The Way It Is Currently Used</h4><p>Most developers then turn to Task.detached to work around the first issue: they want to escape the parent task’s isolation / executor and run code on the global concurrent executor (GCE = background thread from Swift Concurrency background pool). But this is a <strong>bad practice.</strong></p><p>First, when you use Task.detached, only the content inside its closure actually runs on the global concurrent executor. Any asynchronous function you await inside that closure still runs <strong>wherever it is declared.</strong> Task.detached has no impact on the behavior or execution context of the function being awaited!</p><pre>struct ContentView: View {<br>    var body: some View {<br>        Button(&quot;Task&quot;) {<br>            Task.detached {<br>                // Run on the GCE<br>                await doSomething()<br>                // Back on the GCE<br>            }<br>        }<br>    }<br>    <br>    private func doSomething() async {<br>        // Run on main actor because of the View protocol<br>    }<br>}</pre><pre>// &lt; Swift 6.2<br>struct ContentView: View {<br>    var body: some View {<br>        Button(&quot;Task&quot;) {<br>            Task.detached {<br>                // Run on the GCE<br>                await doSomething()<br>                // Back on the GCE<br>            }<br>        }<br>    }<br>    nonisolated func doSomething() async {<br>        // Run on the GCE because marked as nonisolated + async<br>    }<br>}</pre><p>In the two examples above, Task.detached <strong>does not change the behavior</strong> of doSomething(). Replacing it with a regular Task would give the <strong>exact same behavior!</strong></p><p>Regarding Swift 6.2 and the new nonisolated(nonsending) setting, nonisolated async functions do indeed depend on the caller’s context. But that is still not a reason to use Task.detached. Apple already provides us with @concurrent, which forces a function to run on the GCE.</p><pre>// Swift 6.2<br>struct ContentView: View {<br>    var body: some View {<br>        Button(&quot;Task&quot;) {<br>            Task.detached {<br>                // Run on the GCE<br>                await doSomething()<br>                // Back on the GCE<br>            }<br>        }<br>    }<br>    @concurrent<br>    func doSomething() async {<br>        // Run on a background thread from the GCE because marked as @concurrent<br>    }<br>}</pre><p>Task.detached is still useless here! A normal Task is the correct tool to use, and your code will automatically hop back to the MainActor when it returns. What you want is:</p><pre>struct ContentView: View {<br>    var body: some View {<br>        Button(&quot;Task&quot;) {<br>            Task {<br>                // Run on the main actor<br>                await doSomething()<br>                // Back on the main actor<br>            }<br>        }<br>    }<br>    @concurrent<br>    func doSomething() async {<br>        // Run on a background thread from the GCE because marked as @concurrent<br>        // &lt; Swift 6.2: Make it nonisolated<br>    }<br>}</pre><p>We have therefore ruled out the possibility of using Task.detached to make a function called inside its closure inherit anything. But maybe you’ll still need, for a completely different reason, to run a task’s body on a background thread, and therefore prevent the task from inheriting its parent executor and force it to run on the GCE. And once again… Task.detached is not the right solution</p><h4>The Correct Approach</h4><p>Task takes a parameter that very few people know about: executorPreference. You can instruct a task to execute on a different executor than the one it would normally inherit. And yes, you can pass the GCE!</p><pre>struct ContentView: View {<br>    var body: some View {<br>        Button(&quot;Task&quot;) {<br>            Task(executorPreference: globalConcurrentExecutor) {<br>                // This closure must run on background for whatever reason<br>                // And this is the correct way to do it<br>            }<br>        }<br>    }<br>}</pre><p>This API, released with iOS 18, is literally designed for this purpose, as Apple <a href="https://developer.apple.com/documentation/swift/globalconcurrentexecutor">states in the documentation</a>:</p><blockquote>You may pass this executor explicitly to a Task initializer as a task executor preference, in order to ensure and document that the task be executed on the global executor, instead of inheriting the enclosing actor’s executor.</blockquote><p>Not only is it made for that, but it’s also much clearer: you explicitly state that the execution of this task will run on Swift Concurrency’s global thread pool.</p><p>It’s even possible to change the executor for an entire scope using withTaskExecutorPreference().</p><p><em>PS: If you have declared a custom executor on an actor, it won’t take your preference into account. But these are very specific cases that I won’t consider.</em></p><p><em>PS 2: You’ll notice that this parameter is also available on Task.detached, because it’s possible to create a custom TaskExecutor and run the detached task on it. Of course, passing the globalConcurrentExecutor to Task.detached would, as you can imagine, make no sense.</em></p><h4>Conclusion</h4><p>So what is Task.detached actually for?</p><p>Well, you just need to compare it with Task(executorPreference: globalConcurrentExecutor):</p><pre>struct ContentView: View {<br>    @TaskLocal static var userID: String = &quot;anonymous&quot;<br>    var body: some View {<br>        Button(&quot;Test Task priority&quot;) {<br>            taskInherits()<br>        }<br>    }<br>    func taskInherits() {<br>        Self.$userID.withValue(&quot;user-123&quot;) {<br>            Task(priority: .low) {<br>                // MainActor isolated<br>                // Priority low<br>                // user-123<br>                Task {<br>                    // MainActor isolated<br>                    // Priority low<br>                    // user-123<br>                    Task {<br>                        // MainActor isolated<br>                        // Priority low<br>                        // user-123<br>                        Task(executorPreference: globalConcurrentExecutor) {<br>                            // isolated to nil<br>                            // Priority low<br>                            // user-123<br>                            Task {<br>                                // isolated to nil<br>                                // Priority low<br>                                // user-123<br>                                Task {<br>                                    // isolated to nil<br>                                    // Priority low<br>                                    // user-123<br>                                }<br>                            }<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>To conclude that Task.detached is useful when, in addition to having to prevent the inheritance of an actor’s isolation and executor, you also need to prevent the inheritance of a priority or/and a @TaskLocal. <strong>That’s it</strong>.</p><p>Have you ever run into a situation like this in your own code? I don’t think so. And that makes sense, because these cases are <strong>extremely uncommon</strong>.</p><p>And it’s even funnier when you consider that preventing priority inheritance has become completely pointless, since you can simply declare a Task with executorPreference on the GCE and the new priority to achieve the same result , but better and more clearly.</p><p>So in summary, Task.detached is only useful for… preventing the inheritance of a @TaskLocal.</p><p>And don’t think about using Task.detached to create lots of parallel tasks, structured concurrency is made for that, and Apple reminds us of it:</p><blockquote>Don’t use a detached unstructured task if it’s possible to model the operation using structured concurrency features like child tasks.</blockquote><p>The whole point was to show you that you don’t need Task.detached. I don’t understand why this API is so widely used when it’s only useful for extremely rare edge cases. In fact, even using executorPreference is a rare case!</p><p>Thank you for reading! Feel free to support the article if you’d like to see more posts about Swift Concurrency!</p><p>Mathis</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8e060ae51a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Alert Handling in SwiftUI: Mapping Optionals to Presentation State]]></title>
            <link>https://medium.com/@matgnt/clean-alert-handling-in-swiftui-mapping-optionals-to-presentation-state-acb4df717c01?source=rss-43a7c410e21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/acb4df717c01</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Mathis Gaignet]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 07:32:10 GMT</pubDate>
            <atom:updated>2025-11-10T07:32:10.071Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1AIReiszpRk0KYjtCLuW6Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sigmund</a> on <a href="https://unsplash.com/photos/red-and-gray-metal-stand-0dM5sa4zfZ8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>During the development of your app, you may encounter situations where multiple alerts need to be presented to the user. A simple way to do this looks like this:</p><pre>struct ContentView: View {<br>    @State private var model = Model()<br>    <br>    var body: some View {<br>        VStack {<br>          // ...<br>        }<br>        .alert(&quot;Alert&quot;, isPresented: $model.showAlert) {<br>            // Buttons for your alert<br>        } message: {<br>            Text(&quot;This is a message for your alert&quot;)<br>        }<br>    }<br>}</pre><p>Just like sheets, the isPresented parameter determines whether the alert will appear when it’s set to true. SwiftUI’s alert also allows you to display a message.</p><p>For an error scenario, you typically have a function that <strong>throws</strong> an error. Once caught, you can set your Boolean state to true, and the alert will be displayed.</p><pre>@Observable<br>final class Model {<br>    var showMapCocktailError = false<br>    var showGetCocktailsError = false<br>    <br>    func someCallingFunction() {<br>        do {<br>            try someThrowingFunction()<br>        } catch .couldntMapCocktails {<br>            showMapCocktailError = true<br>        } catch .failedToGetCocktails {<br>            showGetCocktailsError = true<br>        } catch {<br>            // ...<br>        }<br>    }<br>    <br>    func someThrowingFunction() throws(CocktailErrors) {}<br>}</pre><p>This approach works fine for 2–3 errors, but if you have a use case where many functions might throw errors, you end up implementing a bunch of alerts in your view and declaring multiple Boolean states.</p><pre>var showNetworkError = false<br>var showFileError = false<br>var showPermissionError = false<br>// … and so on</pre><p>What we really need is a generic way to declare <strong>a single alert</strong> that updates depending on the error. This is possible using the presenting data API in SwiftUI.</p><pre>nonisolated<br>func alert&lt;A, T&gt;(<br>    _ title: Text,<br>    isPresented: Binding&lt;Bool&gt;,<br>    presenting data: T?,<br>    @ViewBuilder actions: (T) -&gt; A<br>) -&gt; some View where A : View</pre><p>The presenting parameter works similarly to the .sheet(item: ) parameter on sheets if you’ve used it before. Essentially, you pass a nil value, and as soon as it’s not nil, the alert is shown. It differs slightly from sheets, because with sheets, the item parameter completely replaces the isPresented parameter. For alerts, both parameters exist and <strong>must be true at the same time</strong> to display the alert.</p><h3>Example: Foundation Model Errors</h3><p>Today, I encountered this scenario with Apple’s Foundation Models framework, introduced at WWDC25. Many things can go wrong:</p><ul><li>Is it available on the user’s device?</li><li>Has the user enabled it in the settings?</li><li>Is the model ready?</li></ul><p>And during generation, multiple other errors can occur:</p><pre>case exceededContextWindowSize(LanguageModelSession.GenerationError.Context)<br>case assetsUnavailable(LanguageModelSession.GenerationError.Context)<br>case guardrailViolation(LanguageModelSession.GenerationError.Context)<br>case unsupportedGuide(LanguageModelSession.GenerationError.Context)<br>case unsupportedLanguageOrLocale(LanguageModelSession.GenerationError.Context)<br>case decodingFailure(LanguageModelSession.GenerationError.Context)<br>case rateLimited(LanguageModelSession.GenerationError.Context)<br>case concurrentRequests(LanguageModelSession.GenerationError.Context)<br>case refusal(LanguageModelSession.GenerationError.Refusal, LanguageModelSession.GenerationError.Context)</pre><p>Most of this information is important to show the user, or else they won’t understand what went wrong. Obviously, creating a separate alert for each error would be unmanageable. So how do we handle it?</p><h4>Step 1: Define a Generic Alert Struct</h4><p>We first declare a struct to represent the alert. It will contain a title and a message.</p><pre>struct LanguageError: Identifiable {<br>    let title: String<br>    let message: String<br>    <br>    var id: String { message }<br>}</pre><p>This struct will be used in the presenting parameter. Naturally, we declare it as a state variable initialized to nil:</p><pre>@Observable<br>final class GenerableModel {<br>    var errorDetails: LanguageError?<br>}</pre><h4>Step 2: Catch Errors and Assign the Alert</h4><p>Instead of setting a Boolean to true when an error occurs, we assign our error to an instance of the alert struct:</p><pre>do {<br>    for try await cocktailIdea in streamingResponse {<br>        self.cocktailIdea = cocktailIdea<br>    }<br>} catch LanguageModelSession.GenerationError.unsupportedLanguageOrLocale {<br>    errorDetails = LanguageError(<br>        title: &quot;Unsupported language&quot;,<br>        message: &quot;Apple Intelligence does not support this language.&quot;<br>    )<br>} catch LanguageModelSession.GenerationError.refusal(let refusal, _) {<br>    errorDetails = LanguageError(<br>        title: &quot;Request refused&quot;,<br>        message: try await refusal.explanation.content<br>    )<br>} catch LanguageModelSession.GenerationError.decodingFailure {<br>    errorDetails = LanguageError(<br>        title: &quot;Generation failed&quot;,<br>        message: &quot;Apple Intelligence couldn’t finish mixing your cocktail. Give it another try.&quot;<br>    )<br>} catch LanguageModelSession.GenerationError.assetsUnavailable {<br>    errorDetails = LanguageError(<br>        title: &quot;Apple Intelligence assets unavailable&quot;,<br>        message: &quot;Some required files for Apple Intelligence are missing. Please make sure Apple Intelligence is enabled and try again later.&quot;<br>    )<br>} catch {<br>    errorDetails = LanguageError(<br>        title: &quot;Unknown error&quot;,<br>        message: &quot;Something went wrong.&quot;<br>    )<br>}</pre><p>You can even refactor your code with a function that lives in another file or usecase.</p><pre>struct GenerableErrorUseCase {<br>    private let model = SystemLanguageModel.default<br>    <br>    func mapLanguageError() -&gt; LanguageError? {<br>        switch model.availability {<br>        case .available:<br>            return nil<br>        case .unavailable(.deviceNotEligible):<br>            return LanguageError(<br>                title: &quot;Device not supported&quot;,<br>                message: &quot;Your device does not support Apple Intelligence.&quot;<br>            )<br>        case .unavailable(.appleIntelligenceNotEnabled):<br>            return LanguageError(<br>                title: &quot;Apple Intelligence disabled&quot;,<br>                message: &quot;You need to enable Apple Intelligence in Settings.&quot;<br>            )<br>        case .unavailable(.modelNotReady):<br>            return LanguageError(<br>                title: &quot;Apple Intelligence isn&#39;t ready yet&quot;,<br>                message: &quot;Please check your network connection try again in a few moments&quot;<br>            )<br>        case .unavailable(let other):<br>            return LanguageError(title: &quot;Something went wrong&quot;, message: &quot;Reason: \(other)&quot;)<br>        }<br>    }<br>}<br><br><br>@Observable<br>final class GenerableModel {<br>    let errorUseCase = GenerableErrorUseCase()<br><br>    func generate() async {<br>        do {<br>            for try await cocktailIdea in streamingResponse {<br>                self.cocktailIdea = cocktailIdea<br>            }<br>        } catch let error as LanguageModelSession.GenerationError {<br>            errorDetails = await errorUseCase.mapGenerationError(error)<br>        } catch {<br>            print(&quot;Unknown error&quot;)<br>        }<br>    }<br>}</pre><h4>Step 3: Declare a Single Alert in Your Root View</h4><pre>struct GenerationView: View {<br>    @State private var model = GenerableModel()<br>    <br>    var body: some View {<br>        VStack {<br>            // subviews + navigation.. <br>        }<br>        .alert(<br>            Text(model.errorDetails?.title ?? &quot;Error&quot;),<br>            isPresented: Binding(<br>                get: { model.errorDetails != nil },<br>                set: { newValue in<br>                    if !newValue {<br>                        model.errorDetails = nil<br>                    }<br>                }<br>            ),<br>            presenting: model.errorDetails<br>        ) { _ in<br>            // Your buttons<br>        } message: { details in<br>            Text(details.message)<br>        }<br>    }<br>}</pre><p>As mentioned earlier, both the isPresented and presenting parameters need to be true for the alert to show. We can create a binding that reflects the presenting state. As soon as a presenting value is set, isPresented will also become true.</p><p>This logic can be extracted into an extension if you want.</p><pre>extension Binding where Value: Equatable {<br>    static func isPresent&lt;T&gt;(_ source: Binding&lt;T?&gt;) -&gt; Binding&lt;Bool&gt; where Value == Bool {<br>        Binding&lt;Bool&gt;(<br>            get: { source.wrappedValue != nil },<br>            set: { newValue in<br>                if !newValue {<br>                    source.wrappedValue = nil<br>                }<br>            }<br>        )<br>    }<br>}<br><br>.alert(<br>    Text(model.errorDetails?.title ?? &quot;Error&quot;),<br>    isPresented: .isPresent($model.errorDetails),<br>    presenting: model.errorDetails<br>) { _ in<br>    // Your buttons<br>} message: { details in<br>    Text(details.message)<br>}</pre><p>And that’s it! Now, whenever any function that throws an error is called, all errors can be routed to this single alert, keeping your code clean and avoiding multiple Boolean states.</p><p>It’s also possible to take a broader approach and implement a full alert router. I prefer grouping them locally when there aren’t too many, but it’s up to you depending on your use case!</p><p>Thanks for reading ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acb4df717c01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of SwiftData in 2025: From Scattered Pieces to a Masterpiece]]></title>
            <link>https://medium.com/@matgnt/the-art-of-swiftdata-in-2025-from-scattered-pieces-to-a-masterpiece-1fd0cefd8d87?source=rss-43a7c410e21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fd0cefd8d87</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mathis Gaignet]]></dc:creator>
            <pubDate>Fri, 07 Nov 2025 05:28:01 GMT</pubDate>
            <atom:updated>2025-11-16T04:06:43.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IqazQ1QVsJ4keV5J_nG4IQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@floeriohh?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Oliver Flöricke</a> on <a href="https://unsplash.com/photos/stack-of-cargo-containers-with-white-crane-tvTmdKQkG_4?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>SwiftData is a framework unveiled at WWDC23, designed to eventually replace CoreData. Well, you won’t truly be parting ways with CoreData since it still powers SwiftData under the hood. What changes is the syntax. It’s now more concise, readable, and declarative (basically everything we love in a modern framework that integrates seamlessly with SwiftUI).</p><p>On top of that, it keeps smooth, built-in integration with CloudKit.</p><p>I know many of you have run into frustrations with this framework, especially because it enforces a certain logic in your view with @Query and modelContext. Let’s be clear: my goal here isn’t to show you how to fight the framework, but rather how to use it intelligently and cleanly.</p><p>Let’s take a step back. I’ll go over the basics of the framework before diving into more technical details, so you can follow the thought process that led me to build this final architecture.</p><p><em>PS: I won’t be covering relationships or migrations in this article, since we’re focusing purely on architecture.</em></p><p>SwiftData revolves around two key components: the ModelContainer and the ModelContext.</p><h4>ModelContainer</h4><p>This is the persistence backend, an object that manages the schema(s) of your application and handles the configuration of model storage.</p><p>A schema is an object that maps model classes to data in the model store, and also helps with the migration of that data between releases if you’re using migrations.</p><p>It handles persistence by deciding whether data is stored in memory or on disk, ensures consistency by keeping storage in a usable and coherent state, coordinates operations to perform reads and writes efficiently, manages migrations by automatically evolving the schema across versions, and, if configured, synchronizes data across devices via CloudKit.</p><p>The optional configuration parameter allows you to customize the storage file URL, the CloudKit container to use, the storage mode (in-memory or persistent), the container group identifiers, and even multiple configurations if you want to separate different object graphs.</p><h4>ModelContext</h4><p>This object lets you fetch, insert, delete models, and commit changes to disk (that is, to the container). Think of it as your command interface for talking to the container. Its main responsibilities include fetching data from the container as needed, keeping modifications in memory (insertions, updates, deletions), persisting changes to the ModelContainer when context.save() is invoked, and cleaning up objects when they are no longer referenced.</p><h4>Model macro</h4><p>Now that you’re familiar with the container and the context, let’s declare a model which will represents the object you want SwiftData to persist. Unlike some other Swift data structures, we don’t use struct here. Instead, we define a class and annotate it with the @Model macro:</p><pre>@Model<br>final class Book {<br>    var title: String<br>    var author: String<br>    var releaseDate: Date<br>    var language: String<br>    var pages: Int<br>    var format: Format<br>    var isRead: Bool<br>    var isFavorited: Bool<br>    var isbn: String<br>    <br>    init(<br>         title: String = &quot;&quot;,<br>         author: String = &quot;&quot;,<br>         releaseDate: Date = Date(),<br>         language: String = &quot;&quot;,<br>         pages: Int = 0,<br>         format: Format = .hardcover,<br>         isRead: Bool = false,<br>         isFavorited: Bool = false,<br>         isbn: String = &quot;&quot;<br>        )<br>}</pre><p>Note that I’m providing default values for all parameters to allow flexible object creation. I can create a completely empty Book() or partially fill it as needed.</p><p>The @Model macro serves several purposes. At its core, it’s a single keyword that, under the hood, generates a lot of logic to simplify your code and make it more readable. Of course, like any macro or property wrapper in SwiftUI, it can feel a bit strange to <em>trust</em> the framework by writing a single declarative keyword that generates a ton of code, instead of controlling everything imperatively like in UIKit. That magic can be disconcerting at first, which is why I believe it’s important to understand the core mechanisms at work.</p><p>Anyhow, here are the key elements that @Model generates:</p><ul><li><strong>Conformance to </strong><strong>PersistentModel</strong></li></ul><p>The macro makes your class conform to PersistentModel, which provides standard get and set functions. Your data can now be persisted automatically. This allows your model to communicate with the ModelContext through an internal BackingData layer, enabling insert, <br>update, and delete operations to be tracked automatically.</p><ul><li><strong>Conformance to </strong><strong>@Observable</strong></li></ul><p>All changes to the class are handled through the different methods of the macro’s ObservationRegistrar. If you want to learn more about the Observation framework, check out <a href="https://fatbobman.com/en/posts/mastering-observation/">this article by Fatbobman.</a></p><p>Now that we have our model, let’s wire it up in App.swift.</p><pre>import SwiftUI<br>import SwiftData<br><br>@main<br>struct LibraryApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            Library()<br>                .modelContainer(for: Book.self)<br>        }<br>    }<br>}</pre><p>This is the simplest way to declare a container. With .modelContainer(for:) , we provide our previously declared model . We can setup as many models as we want. The container sets up a ModelContext for this container (called the mainContext) and injects it into the environment, making it available throughout your SwiftUI views to perform insertions, deletions, and save operations.</p><p>It’s worth noting that you can have multiple contexts and/or containers, but when you use .modelContainer(for:) on your @main, your application receives a general container along with a main context associated with that container.</p><pre>struct Library: View {<br>    @Environment(\.modelContext) private var context<br>    <br>    var body: some View {<br>        Button(&quot;Insert a book&quot;) {<br>            context.insert(Book(title: &quot;A book&quot;))<br>        }<br>    }<br>}</pre><p>Here, I’m inserting a new object into the container via the ModelContext environment, which corresponds to the mainContext of my ModelContainer.</p><p>Remember, @Model implicitly made our class conform to @Observable. This means we can observe changes in real time, just as we would with any @Observable class.</p><h4>Query Macro</h4><p>However, unlike @State, which stores and owns its value, SwiftData provides @Query, which acts as a <em>window</em> into the ModelContext. @Query <strong>doesn’t store data</strong>. It fetches it on demand from the persistent store and automatically refreshes when the underlying models change, thanks to @Observable. Additionally, @Query provides powerful options for filtering and sorting at the fetch level. For this topic, if you want to learn more about dynamic queries and are already familiar with SwiftData, here’s <a href="https://medium.com/@matgnt/deep-dive-into-dynamic-swiftdata-queries-9d029568dd8f">an article I wrote about it.</a></p><p>So basically, it’s pretty much similar to the @FetchRequest property wrapper we had with CoreData.</p><p>I’m going to explain it in more detail, as this will be important for the rest of the article. So, like @Model, @Query is also a macro.</p><p>When you write:</p><pre>@Query var books: [Book]</pre><p>The macro actually generates this code under the hood:</p><pre>{<br>    get {<br>        _books.wrappedValue<br>    }<br>}<br>private(set) var _books: SwiftData.Query&lt;[Book].Element, [Book]&gt; = .init()</pre><p>This generated SwiftData.Query struct has two key characteristics:</p><ul><li><strong>It accessed the </strong><strong>ModelContext via the environment</strong></li></ul><p>This means you cannot use @Query without first providing a .modelContainer(for:) in your app, otherwise you’ll have a compiler error</p><blockquote>Set a .modelContext in view’s environment to use Query</blockquote><ul><li><strong>It conforms to the </strong><strong>DynamicProperty protocol</strong></li></ul><pre>@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)<br>@MainActor @preconcurrency public struct Query&lt;Element, Result&gt; : DynamicProperty where Element : PersistentModel {}</pre><p>In fact, this protocol expects an update() function, which is <strong>called every time the view’s body is recomputed</strong>, ensuring that data is always up to date:</p><pre>/// Updates the underlying value of the stored value.<br>///<br>/// SwiftUI calls this function before rendering a view&#39;s<br>/// ``View/body-swift.property`` to ensure the view has the most recent<br>/// value.<br>nonisolated public func update()</pre><p>For those of you who have implemented your own @propertyWrapper, you’ve probably encountered this protocol before. It allows, for instance, a @State in a struct to trigger update() on every recomputation of the body caused by changes in that state.</p><p>To summarize, Book is a @Model that I can insert, modify, or delete through the ModelContext. Changes are initially <strong>stored in a temporary state </strong>which I can access if needed:</p><pre>public var insertedModelsArray: [any PersistentModel] { get }<br>public var changedModelsArray: [any PersistentModel] { get }<br>public var deletedModelsArray: [any PersistentModel] { get }</pre><p>The way Observable, ModelContext, and @Query communicate isn’t explicitly detailed in the documentation, but at a high level, it works something like this:</p><pre>public var persistentBackingData: any SwiftData.BackingData&lt;Book&gt; {<br>    get {<br>        return _$backingData<br>    }<br>    set {<br>        _$backingData = newValue<br>    }<br>}</pre><p>When you call save(), the ModelContext triggers didSave() and notifies the BackingData (the interface that allows your model to communicate with the ModelContainer) that the data needs to be refreshed. BackingData calls setValue and at some point, @Observable is triggered. SwiftUI knows that a redraw is needed. Before recomputing the view’s body, SwiftUI calls the update() function on all DynamicProperty instances (including @Query), allowing it to re-fetch the latest data from the ModelContext. The changes stored in insertedModelsArray, changedModelsArray, and deletedModelsArray are then reflected on screen.</p><pre>struct Library: View {<br>    @Environment(\.modelContext) private var context<br>    @Query var books: [Book]<br>    <br>    var body: some View {<br>        Button(&quot;Insert a book&quot;) {<br>            context.insert(Book(title: &quot;A book&quot;))<br>        }<br>        List(books) { book in<br>            Text(book.title)<br>        }<br>    }<br>}</pre><p>Now, every time I press “Insert a book”, the new object appears immediately in my view.</p><h3>The Requirements</h3><p>After a long introduction, we now have a solid grasp of the framework and can start building something more concrete.</p><p>The goal is simple: I want to display a library of books. Users should be able to add new books with their properties (like title and author), edit them, and delete them, while seeing everything update in real time.</p><p>There are a few requirements I want to define before we start.</p><p>First, users should be able to <strong>cancel a creation or an edit in progress</strong>. That means the view will include a toolbar with at least two buttons: one for canceling and one for saving.</p><p>Naturally, the <strong>creation and editing views should be the same</strong>, since we’re dealing with the same data and want to modify it in place.</p><p>A perfect example of this set of requirements is the Contacts app. Go ahead, open it, try creating a new contact, fill in a few fields, then cancel the creation. Do the same thing with editing an existing contact.</p><p>It feels simple when you use it, but in practice, achieving that kind of clean behavior is <strong>surprisingly tricky</strong> with SwiftData.</p><p>In terms of architecture, I want something scalable that emphasizes simplicity, readability, and clarity. No boilerplate, no duplication. The view should only display data, without needing to know anything about the underlying logic.</p><h3>The scattered Architecture</h3><p>Let’s take a look together at bad examples. The first approach that probably comes to mind is…</p><pre>struct Library: View {<br>    @Environment(\.modelContext) private var context<br>    @Query var books: [Book]<br>    @State private var showEditSheet = false<br>    <br>    var body: some View {<br>        NavigationStack {<br>            List(books) { book in<br>                Text(book.title)<br>            }<br>            .navigationTitle(&quot;Library&quot;)<br>            .toolbar {<br>                Button(&quot;Add a book&quot;, systemImage: &quot;plus&quot;) {<br>                    showEditSheet = true<br>                }<br>            }<br>        }<br>        .sheet(isPresented: $showEditSheet) {<br>            NavigationStack {<br>                UpsertView()<br>            }<br>        }<br>    }<br>}<br><br>struct UpsertView: View {<br>    @Environment(\.dismiss) private var dismiss<br>    @Environment(\.modelContext) private var context<br>    // Wow...<br>    @State private var title = &quot;&quot;<br>    @State private var author = &quot;&quot;<br>    @State private var releaseDate = Date()<br>    @State private var language = &quot;&quot;<br>    @State private var pages = 0<br>    @State private var format: Format = .ebook<br>    @State private var isRead = false<br>    @State private var isFavorited = false<br>    @State private var isbn = &quot;&quot;<br>    <br>    var body: some View {<br>        Form {<br>            Section {<br>                TextField(&quot;Title&quot;, text: $title)<br>                TextField(&quot;Author&quot;, text: $author)<br>                TextField(&quot;Language&quot;, text: $language)<br>            }<br>            /// ...<br>        }<br>        .toolbar {<br>            Button(&quot;Save&quot;) {<br>                let newBook = Book(<br>                    title: title,<br>                    author: author,<br>                    releaseDate: releaseDate,<br>                    language: language,<br>                    pages: pages,<br>                    format: format,<br>                    isRead: isRead,<br>                    isFavorited: isFavorited,<br>                    isbn: isbn<br>                )<br>                context.insert(newBook)<br>                dismiss()<br>            }<br>            Button(&quot;Cancel&quot;) {<br>                dismiss()<br>            }<br>        }<br>    }<br>}</pre><p>Let’s say, worst case, we’ll use a ViewModel to keep things organized. For now, we’ve covered the basics:</p><ul><li>I can create a book with its properties</li><li>I can see it appear in the ModelContainer.</li></ul><p>But we can’t reuse this view for editing yet, because <strong>there’s no way to tell whether we’re creating a new item or updating an existing one</strong>.</p><p>Let’s pass the object into the view so we can check that.</p><pre>    let editBook: Book?<br>    <br>    init(book: Book? = nil) {<br>        self.editBook = book<br>        <br>        if let book {<br>            _title = State(wrappedValue: book.title)<br>            _author = State(wrappedValue: book.author)<br>            _releaseDate = State(wrappedValue: book.releaseDate)<br>            _language = State(wrappedValue: book.language)<br>            _pages = State(wrappedValue: book.pages)<br>            _format = State(wrappedValue: book.format)<br>            _isRead = State(wrappedValue: book.isRead)<br>            _isFavorited = State(wrappedValue: book.isFavorited)<br>            _isbn = State(wrappedValue: book.isbn)<br>        }<br>    }<br><br>    private func saveBook() {<br>        // Edit mode<br>        if let editBook {<br>            editBook.title = title<br>            editBook.author = author<br>            editBook.releaseDate = releaseDate<br>            editBook.language = language<br>            editBook.pages = pages<br>            editBook.format = format<br>            editBook.isRead = isRead<br>            editBook.isFavorited = isFavorited<br>            editBook.isbn = isbn<br>        } else {<br>            // Create mode<br>            let newBook = Book(<br>                title: title,<br>                author: author,<br>                releaseDate: releaseDate,<br>                language: language,<br>                pages: pages,<br>                format: format,<br>                isRead: isRead,<br>                isFavorited: isFavorited,<br>                isbn: isbn<br>            )<br>            context.insert(newBook)<br>        }<br>        try? context.save()<br>        dismiss()<br>    }</pre><p>And just like that, I’ve checked off my set of requirements. That’s it for the article. Do this for all your models, and you’re good to go. Alright, joking aside, I think you’re starting to see how quickly this can get messy. Here I have a single model with only nine properties, and it’s already a bit of a nightmare.</p><p>On top of that, my model has <strong>no relationships</strong>. If it did, I couldn’t even manage this setup without running into deep copy versus shallow copy issues, since relationships would also be @Model classes. So I’d have to handle each of those <strong>independently every time</strong>.</p><p>Now imagine having three models, each with one or more relationships. I don’t even want to think about the code that would require.</p><h3>The Good Architecture</h3><p>With the arrival of the @Observable framework, SwiftUI gave us a new property wrapper.</p><h4>Bindable Property Wrapper</h4><p>@Bindable was introduced to replace the Combine observation system with @ObservedObject and @Published. It’s a property wrapper that lets you create bindings directly to the properties of an @Observable object. Essentially, it’s like manually passing every single property of an object as a @Binding to your view.</p><pre>struct Library: View {<br>    @Environment(\.modelContext) private var context<br>    @Query var books: [Book]<br>    @State private var showEditSheet = false<br>    <br>    var body: some View {<br>        NavigationStack {<br>            List(books) { book in<br>                NavigationLink {<br>                    UpsertView(book: book)<br>                } label: {<br>                    Text(book.title)<br>                }<br>            }<br>            .navigationTitle(&quot;Library&quot;)<br>            .toolbar {<br>                Button(&quot;Add a book&quot;, systemImage: &quot;plus&quot;) {<br>                    showEditSheet = true<br>                }<br>            }<br>        }<br>        .sheet(isPresented: $showEditSheet) {<br>            NavigationStack {<br>                UpsertView(book: Book())<br>            }<br>        }<br>    }<br>}<br><br>struct UpsertView: View {<br>    @Environment(\.dismiss) private var dismiss<br>    @Environment(\.modelContext) private var context<br>    @Bindable var book: Book<br>    <br>    var body: some View {<br>        Form {<br>            Section {<br>                TextField(&quot;Title&quot;, text: $book.title)<br>                TextField(&quot;Author&quot;, text: $book.author)<br>                TextField(&quot;Language&quot;, text: $book.language)<br>            }<br>            // ...<br>        }<br>    }<br>}</pre><p>And now it gets interesting: with a single line, I can directly bind to either a brand new object or an object already persisted in the ModelContainer.</p><p>So, are we done? Not quite. Another major issue comes up. With @Bindable, I’m directly tied to the object itself. That’s great because we can use the same view without 50 lines of conditional logic, but the problem is that the user can no longer cancel an edit in progress.</p><p>It’s not a big deal if you can’t do this for a very small model with just a couple of strings — the user can always go back and change the values. In that case, you can stop here and go with a simple @Bindable.</p><p>But when you have ten or fifteen properties, and the user selects the wrong object to edit or simply wants to cancel their changes, they definitely don’t want to see all fifteen fields updated immediately without having confirmed anything.</p><p>Furthermore, if you check out apps like Contacts, Calendar, Reminders or Photos, you’ll notice that Apple really cares about this aspect of the user experience.</p><p>So, Book is a class, which makes it impossible to implement any kind of “smart” temporary storage using something like onAppear + cancel button.</p><p>I’m going to immediately rule out using SwiftData’s undo manager or rollback() function paired with autosaveEnabled = false. The first one only works on objects that have already been saved — which isn’t what I want here, since I don’t want them persisted yet. The second one is highly unpredictable. It requires constantly switching autosaveEnabled on and off throughout your project, only to end up with a very unstable result that seems to depend on your model’s data and view structure.</p><p>If any of you have managed to achieve predictable behavior with rollback() on highly complex and variable data models, I’d be very curious to see how you implemented it. Either way, the final architecture I came up with is still super compact and robust.</p><p>So what options do we have left? I can combine the two approaches: use @Bindable in the view, while manually saving snapshots of the object’s properties.</p><pre>protocol Rollbackable {<br>    associatedtype Snapshot<br>    func createSnapshot() -&gt; Snapshot<br>    func restore(from snapshot: Snapshot)<br>}<br><br>extension ModelContext {<br>    private static var currentSnapshot: Any?<br><br>    func registerSnapshot&lt;T: PersistentModel &amp; Rollbackable&gt;(_ object: T) {<br>        Self.currentSnapshot = object.createSnapshot()<br>    }<br><br>    func rollbackSnapshot&lt;T: PersistentModel &amp; Rollbackable&gt;(_ object: T) {<br>        guard let snapshot = Self.currentSnapshot as? T.Snapshot else { return }<br>        object.restore(from: snapshot)<br>        Self.currentSnapshot = nil<br>    }<br>}<br><br>extension Book: Rollbackable {<br>    struct Snapshot {<br>        let title: String<br>        let author: String<br>        let releaseDate: Date<br>        let language: String<br>        let pages: Int<br>        let format: Format<br>        let isRead: Bool<br>        let isFavorited: Bool<br>        let isbn: String<br>    }<br><br>    func createSnapshot() -&gt; Snapshot {<br>        Snapshot(<br>            title: title,<br>            author: author,<br>            releaseDate: releaseDate,<br>            language: language,<br>            pages: pages,<br>            format: format,<br>            isRead: isRead,<br>            isFavorited: isFavorited,<br>            isbn: isbn<br>        )<br>    }<br><br>    func restore(from snapshot: Snapshot) {<br>        title = snapshot.title<br>        author = snapshot.author<br>        releaseDate = snapshot.releaseDate<br>        language = snapshot.language<br>        pages = snapshot.pages<br>        format = snapshot.format<br>        isRead = snapshot.isRead<br>        isFavorited = snapshot.isFavorited<br>        isbn = snapshot.isbn<br>    }<br>}</pre><p>I could register a snapshot in onAppear and restore it in the cancel button.</p><p>Hmm, not really ideal. We’d just be reintroducing boilerplate that we removed just before.</p><p>At that point, I thought to myself, there has to be a better solution. After all, Apple itself promotes the use of @Bindable in SwiftData, as shown in <a href="https://developer.apple.com/videos/play/wwdc2023/10154">Build an App with SwiftData (WWDC23)</a>.</p><p>Sure, the app works, and like I said, for simple CRUD operations, it’s fine. But I want the user to be able to cancel an edit, just like Apple does in their apps.</p><p>So I did a bit of digging and I quickly came across <a href="https://www.hackingwithswift.com/quick-start/swiftdata/how-to-discard-changes-to-a-swiftdata-object">this on HackingWithSwift</a>.</p><pre>struct EditingView: View {<br>    @Environment(\.dismiss) var dismiss<br>    @Bindable var issue: Issue<br><br>    var modelContext: ModelContext<br><br>    init(issueID: PersistentIdentifier, in container: ModelContainer) {<br>        modelContext = ModelContext(container)<br>        modelContext.autosaveEnabled = false<br>        issue = modelContext.model(for: issueID) as? Issue ?? Issue(name: &quot;New Issue&quot;)<br>    }<br><br>    var body: some View {<br>        Form {<br>            TextField(&quot;Edit the name&quot;, text: $issue.name)<br>        }<br>        .toolbar {<br>            Button(&quot;Discard&quot;) {<br>                dismiss()<br>            }<br><br>            Button(&quot;Save&quot;) {<br>                try? modelContext.save()<br>                dismiss()<br>            }<br>        }<br>    }<br>}</pre><p>Use a separate context for editing while disabling autosave…? It seems like a solid approach! However, there’s one somewhat obscure function in this code. Let’s see what the documentation says about it.</p><pre>func model(for persistentModelID: PersistentIdentifier) -&gt; any PersistentModel</pre><blockquote>Returns the persistent model for the specified identifier. Return value -&gt; The identified persistent model, if known to the context; otherwise, an unsaved model with its persistentModelID property set to persistentModelID.</blockquote><p>Yeah, well, the documentation is a bit shaky… The main thing to remember is that if the model exists in the ModelContainer, we will be able to create a copy of it into a context other than the main context. We will run some print statements to check this out.</p><p>Let’s try this into our app.</p><pre>struct Library: View {<br>    @Environment(\.modelContext) private var context<br>    @Query var books: [Book]<br>    @State private var showEditSheet = false<br>    @State private var book: Book?<br>    <br>    var body: some View {<br>        NavigationStack {<br>            List(books) { book in<br>                Text(book.title)<br>                    .onTapGesture {<br>                        self.book = book<br>                    }<br>            }<br>            .navigationTitle(&quot;Library&quot;)<br>            .toolbar {<br>                Button(&quot;Add a book&quot;, systemImage: &quot;plus&quot;) {<br>                    self.book = Book()<br>                }<br>            }<br>        }<br>        .sheet(item: $book) { book in<br>            NavigationStack {<br>                let _ = print(&quot;Same as main before? \(book.modelContext === context)&quot;)<br>                UpsertView(bookID: book.persistentModelID, container: context.container)<br>            }<br>        }<br>    }<br>}<br><br>struct UpsertView: View {<br>    @Environment(\.dismiss) private var dismiss<br>    @Environment(\.modelContext) private var context<br>    @Bindable var book: Book<br>    <br>    var editContext: ModelContext<br><br>    init(bookID: PersistentIdentifier, container: ModelContainer) {<br>        let editContext = ModelContext(container)<br>        editContext.autosaveEnabled = false<br>        self.editContext = editContext<br>        self.book = editContext.model(for: bookID) as? Book ?? Book()<br>    }<br>    <br>    var body: some View {<br>        let _ = print(&quot;Same as main after? \(book.modelContext === context)&quot;)<br>        Form {<br>            Section {<br>                TextField(&quot;Title&quot;, text: $book.title)<br>                TextField(&quot;Author&quot;, text: $book.author)<br>                TextField(&quot;Language&quot;, text: $book.language)<br>            }<br>            // ...<br>        }<br>        .toolbar {<br>            Button(&quot;Save&quot;) {<br>                try? editContext.save()<br>                dismiss()<br>            }<br>            Button(&quot;Cancel&quot;) {<br>                dismiss()<br>            }<br>        }<br>    }<br>}</pre><pre>Same as main before? true<br>Same as main after? false</pre><p>Alright, perfect, we’ve confirmed what we wanted. The book is now in a different context than the main one, and all modifications will happen on it.</p><p>At this point, I ran into several issues. First, if you keep the previous navigation logic, it won’t work because NavigationLink(destination: ) loads the view before it even appears. As a result, it won’t be rebuilt each time, and the content of the TextField will be incorrect.</p><p>There are several solutions, such as using a NavigationLink(value: ) paired with .navigationDestination(for: ), but for the sake of simplicity in my app, I decided to use a single sheet for both creation and editing. I therefore changed its implementation to .sheet(item: ).</p><p>Now, our @Bindable var book: Book is created with a separate context using the ModelContext’s .model(for: ) function, so we can edit it safely. If you remember from the introduction, @Query shows the values from the ModelContext even if they haven’t been persisted yet. But here, our @Query uses the mainContext, while we’re working on the editContext. That means changes aren’t reflected in our view. On top of that, every time we leave this view, the editContext is completely destroyed.</p><p>Unfortunately, most examples I found online using this kind of approach didn’t consider the case where the object is <strong>created and edited in the same view</strong>. If you try to tap on “Add a book” the app would crash instantly.</p><pre>SwiftData/BackingData.swift:1037: Fatal error: This model instance <br>was invalidated because its backing data could no longer be found the store. <br>PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(backing: SwiftData.PersistentIdentifier.<br>PersistentIdentifierBacking.temporaryIdentifier(SwiftData.TemporaryPersistentIdentifierImplementation)))</pre><p>What we’re doing here is using the PersistentIdentifier of our object to fetch this object in a different context, thanks to the context.model(for: ) function.</p><p>The issue is that a new, uninserted object doesn’t really have a PersistentIdentifier — well, technically it does, but <strong>it’s in a temporary state.</strong> You can see it on the last line of the latest error above. Every object has a PersistentIdentifier, but objects that haven’t been inserted yet only have a temporary ID, which isn’t enough to recreate a model from that object.</p><p>That’s why book.persistentModelID <strong>is not optional</strong>. An object always has an ID, but if it hasn’t been inserted into the ModelContainer yet, our code will crash when calling context.model(for: ).</p><p>Strangely enough, this contradicts what the documentation suggests, as we’re supposed to have an <em>unsaved model</em>. Furthermore, this function doesn’t even throw.</p><p>To make matters worse, there’s no way to check whether the PersistentIdentifier is temporary or permanent. So how do we differentiate between a creation and an edit?</p><p>At first, I thought about fetching the entire database to check if the actual book already existed, in which case it would be an edit. But fetching the whole model every time quickly became a performance bottleneck, and I ran into context errors between the one I was fetching, the one I was inserting into, and the one I was saving.</p><p>In fact, there’s something else that separates an uninserted object from an inserted one: its context.</p><pre>public var modelContext: ModelContext? { get }</pre><p>PersistentModel provides a property that returns the object’s current context, if one exists.</p><p>So we can check whether a book has a context using book.modelContext. In fact, when the object is inserted from the edit context, this property will point to that context. Once it’s saved to the container and refetched via @Query, its context switches back to the main one. That’s why we have to manually set it back to the edit context each time. But ultimately, all we care about is that the object has a context, and as you’ve seen, <strong>any object saved in the container will always have one</strong>, so we know that if book.modelContext != nil, then <strong>it’s an edit</strong>.</p><p>Okay, so instead of passing the ID, we can pass the entire book. We will still be able to provide the ID in the init() anyway.</p><pre>struct Library: View {<br>    @Environment(\.modelContext) private var context<br>    @Query var books: [Book]<br>    @State private var showEditSheet = false<br>    @State private var book: Book?<br>    <br>    var body: some View {<br>        NavigationStack {<br>            List(books) { book in<br>                Text(book.title)<br>                    .onTapGesture {<br>                        self.book = book<br>                    }<br>            }<br>            .navigationTitle(&quot;Library&quot;)<br>            .toolbar {<br>                Button(&quot;Add a book&quot;, systemImage: &quot;plus&quot;) {<br>                    self.book = Book()<br>                }<br>            }<br>        }<br>        .sheet(item: $book) { book in<br>            NavigationStack {<br>                UpsertView(book: book, container: context.container)<br>            }<br>        }<br>    }<br>}<br><br>struct UpsertView: View {<br>    @Environment(\.dismiss) private var dismiss<br>    @Environment(\.modelContext) private var context<br>    @Bindable var book: Book<br>    <br>    var editContext: ModelContext?<br><br>    init(book: Book, container: ModelContainer) {<br>        if book.modelContext != nil {<br>            let editContext = ModelContext(container)<br>            editContext.autosaveEnabled = false<br>            self.editContext = editContext<br>            self.book = editContext.model(for: book.persistentModelID) as! Book<br>        } else {<br>            self.book = book<br>        }<br>    }<br>    <br>    var body: some View {<br>        Form {<br>            Section {<br>                TextField(&quot;Title&quot;, text: $book.title)<br>                TextField(&quot;Author&quot;, text: $book.author)<br>                TextField(&quot;Language&quot;, text: $book.language)<br>            }<br>            // ...<br>        }<br>        .toolbar {<br>            Button(&quot;Save&quot;) {<br>                if book.modelContext == nil {<br>                    context.insert(book)<br>                    try? context.save()<br>                } else {<br>                    try? editContext?.save()<br>                }<br>                dismiss()<br>            }<br>            Button(&quot;Cancel&quot;) {<br>                dismiss()<br>            }<br>        }<br>    }<br>}</pre><p>At that point, my logic was:</p><p>Okay, I want to create a brand-new object through the main context, just like I normally would in SwiftData. So if the book doesn’t have a context, meaning it’s new, I assign it directly to the book property and use the main context for the insert and save logic. Otherwise, it’s an edit, so I use my custom edit context.</p><p>And once again, <strong>I ran into another bug</strong>. When you create an object, save it through the main context, then immediately try to edit it and save it <strong>from another context</strong>, it fails. Your changes are not persisted.</p><p><strong>The issue:</strong></p><p>From what I’ve seen in the docs, when context.save() is called, other contexts don’t immediately see those changes.</p><p>You have to wait for the didSave notifications to propagate and for the contexts to synchronize.</p><p>You can actually verify this by checking whether the book still has unpersisted changes using book.hasChanges:</p><pre>.onTapGesture {<br>    print(&quot;Has changes \(book.hasChanges)&quot;)<br>    self.book = book<br>}<br><br>var body: some View {<br>    let _ = print(&quot;Has changes in the view \(book.hasChanges)&quot;)<br>}</pre><p>And here’s the output:</p><pre>• Has changes: true<br>• Has changes in the view: false<br>-----<br>• Has changes: false<br>• Has changes in the view: false</pre><p>When I open UpsertView on a freshly created book, you can see it still has unpersisted changes even though I just saved it.</p><p>In the view, however, it shows false, since there are no pending changes in the edit context.</p><p>If you wait a bit after opening UpsertView, then close and reopen it, you’ll see the second print shows everything is fine: the object is now persisted, has no pending changes, and I haven’t even touched a single text field (otherwise you’d see Has changes in the view: true). Now and <strong>only now</strong>, you can edit it from the other context.</p><p>Well, that’s a bit annoying. I create an object, and if I immediately realize I made a mistake, I can’t even edit it right away.</p><p>So close, yet so far. What do we do then, check if book.hasChanges = true and skip switching contexts? That would break rollback.</p><p>The solution I came up with is simple, but counterintuitive. We insert and save from a <strong>single context</strong> : the edit context.</p><p>I found this counterintuitive at first because the entire purpose of using a separate context is to prevent @Bindable from immediately reflecting changes in our main context. This is the <strong>root of our problem</strong>.</p><p>Inserting a new book has never been an issue on its own, so why bother doing it with a custom context at all?</p><p>Well, remember , a context is just an interface between your actions and the storage layer. No matter where you insert or save data from, it all ends up in the same ModelContainer of your app anyway.</p><p>And by doing so, we completely avoid any didSave delays or synchronization timing issues between two contexts, since we’ll be using <strong>the same one from start to finish</strong>.</p><p>To make this work, let’s adjust our init() and saving logic:</p><pre>init(book: Book, container: ModelContainer) {<br>    let editContext = ModelContext(container)<br>    editContext.autosaveEnabled = false<br>    self.editContext = editContext<br><br>    if book.modelContext != nil {<br>        self.book = editContext.model(for: book.persistentModelID) as! Book<br>    } else {<br>        self.book = book<br>    }<br>}<br><br>Button(&quot;Save&quot;) {<br>    if book.modelContext == nil {<br>        editContext?.insert(book)<br>        try? editContext?.save()<br>    } else {<br>        try? editContext?.save()<br>    }<br>    dismiss()<br>}</pre><p>And there we go, our requirements are fully met. We can now <strong>create</strong>, <strong>cancel</strong>, <strong>edit</strong>, and <strong>cancel edits</strong>, all cleanly and safely.</p><h3>The Masterpiece</h3><p>But I didn’t want to stop there. I wanted something <strong>even better</strong>.</p><p>Sure, I’ve reduced some boilerplate, but I end up with ten lines of initializer code with a messy condition. And if I have multiple <em>upsert</em> views for different models, I’d end up repeating code, creating an edit context over and over again.</p><p>First, let’s remove the init() from UpsertView and pass the object from the parent, which will have been preloaded into the edit context.</p><p>No awkward condition checks in the init(), no container passed in. And now you might be wondering, how are we going to pass the edit context to save the item? Well, we’re going to get a little clever.</p><p>First, we’ll move our edit context creation logic into a compact function as an extension of ModelContext. I named it switch(for: ).</p><pre>extension ModelContext {<br>    func `switch`&lt;T: PersistentModel&gt;(for model: T) -&gt; T {<br>        let ctx = ModelContext(self.container)<br>        ctx.autosaveEnabled = false<br>        guard model.modelContext != nil else {<br>            // Creation<br>            return model<br>        }<br>        // Edit<br>        return ctx.model(for: model.persistentModelID) as? T ?? model<br>    }<br>}</pre><p>The function is generic, allowing it to cover all the different models in your app. Let’s take this opportunity to safely unwrap this optional cast also.</p><p>The problem is that we don’t have the edit context in the view anymore, so our previous logic in the save button won’t work. It is currently encapsulated inside our switch(for: ) function, which means we can’t directly pass it to the view.</p><p>There are several ways to do this; I’ll show you my approach.</p><pre>extension ModelContext {<br>    func `switch`&lt;T: PersistentModel&gt;(for model: T) -&gt; T {<br>        let ctx = ModelContext(self.container)<br>        ctx.autosaveEnabled = false<br>        guard model.modelContext != nil else {<br>            ctx.insert(model) // Insert the new book<br>            return model<br>        }<br>        return ctx.model(for: model.persistentModelID) as? T ?? model<br>    }<br>}</pre><p><strong>I</strong> <strong>insert the book into the edit context before giving it to the view</strong> .</p><p>This way, our book, whether freshly created or already persisted , is switched to a different context and can carry its own source of truth.</p><p>Since our edit context has autosaveEnabled = false, there’s no risk here: as long as we don’t explicitly call save(), the object will never be persisted to the ModelContainer.</p><p>And remember, temporary changes made inside a ModelContext aren’t visible to other contexts anyway, so the object won’t appear inserted anywhere else ! If we were doing this directly with the main context, you would see it appear in your @Query list until you quit the app.</p><p>Then, I’m <strong>overriding</strong> the modelContext environment.</p><pre>.sheet(item: $book) { book in<br>    let book = context.switch(for: book)  <br>    NavigationStack {<br>        UpsertView(book: book)<br>            .environment(\.modelContext, book.modelContext!)<br>    }<br>}</pre><p>Here, I can <em>safely</em> force unwrap. I’m already checking whether the book has a context in my switch(for: ) function, and if it doesn’t, <strong>I explicitly provide one.</strong></p><p>Anyway, it saves us from having to create an edit context variable and pass it down through all the subviews – toolbar or otherwise. Instead, we use the framework’s standard environment.</p><pre>struct UpsertView: View {<br>    @Environment(\.dismiss) private var dismiss<br>    @Environment(\.modelContext) private var context<br>    @Bindable var book: Book<br><br>    var body: some View {<br>        Form {<br>            // ...<br>        }<br>        .toolbar {<br>            Button(&quot;Save&quot;) {<br>                try? context.save()<br>                dismiss()<br>            }<br>            Button(&quot;Cancel&quot;) {<br>                dismiss()<br>            }<br>        }<br>    }<br>}</pre><p>As a result, UpsertView and all of its child views will automatically receive the edit context.</p><p>Now, inserting the new book into the context from the switch(for: ) function serves a dual purpose: it passes the context down to the view, but more importantly, <strong>it unifies our save logic</strong>. I no longer need to compare a new book with one from the container when saving, because both are already inserted. I can simply call try? context.save() and be done with it.</p><p>And you’ll notice that <strong>the view doesn’t know anything about all that</strong>, it just does its job of displaying what it’s given.</p><p>That definitely ticks the scalability box from our requirements. Having a generic switch(for: ) function allows us to apply the same logic to any model. With a more traditional approach, like using snapshots or manually fetching data, the more models you have, the more code you end up writing.</p><h4>One more thing..</h4><p>For those who want to take things even further — we’re almost at perfection, but there are still a couple of small rough edges in our implementation.</p><p>The only minor “issues” left are:</p><ul><li>We have to manually override the environment for UpsertView, otherwise it’ll use the wrong context.</li><li>We have to manually call context.switch(for: ) every time we pass a model into its corresponding <em>upsert</em> view.</li></ul><p>One of those can actually be fixed.</p><p>For the first one — there’s no real magic here. The environment won’t override itself. You <em>could</em> technically skip it and just call book.modelContext?.save() to avoid any crash risk. The reason I didn’t go with that option is because I wanted to keep things aligned with SwiftData’s normal usage pattern.</p><p>It’s not really <em>idiomatic</em> to save from the object’s own context. Any developer familiar with SwiftData would expect to use the environment context as Apple recommends. So overriding it manually feels like the cleanest way to keep everyone on the same page… as long as you remember to do it!</p><p>Now, the second one is <strong>fixable!</strong></p><p>In my current implementation, you might have noticed that I store the book (whether newly created or already persisted ) inside this state variable.</p><pre>@State private var book: Book?</pre><p>Then, I retrieve it in the sheet’s closure and manually assign its new context.</p><pre>.sheet(item: $book) { book in<br>    let book = context.switch(for: book)  <br>    NavigationStack {<br>        UpsertView(book: book)<br>            .environment(\.modelContext, book.modelContext!)<br>    }<br>}</pre><p>You can probably see where this is going…</p><pre>@propertyWrapper<br>struct Switch&lt;T: PersistentModel&gt;: DynamicProperty {<br>    @Environment(\.modelContext) private var context<br>    @State private var value: T?<br>    <br>    var wrappedValue: T? {<br>        get {<br>            value<br>        }<br>        nonmutating set {<br>            if let newValue {<br>                value = context.switch(for: newValue)<br>            } else {<br>                value = nil<br>            }<br>        }<br>    }<br>    <br>    var projectedValue: Binding&lt;T?&gt; {<br>        Binding(<br>            get: { value },<br>            set: { newValue in<br>                if let newValue {<br>                    value = context.switch(for: newValue)<br>                } else {<br>                    value = nil<br>                }<br>            }<br>        )<br>    }<br>    <br>    init(wrappedValue: T? = nil) {<br>        self._value = State(initialValue: wrappedValue)<br>    }<br>}</pre><p>A <strong>generic property wrapper</strong> that automatically switches the model’s context when it’s received, by calling switch(for: ) for you.</p><pre>struct Library: View {<br>    /// ... <br>    @Switch private var book: Book?<br>    <br>    var body: some View {<br>        NavigationStack {<br>            // ...<br>        }<br>        .sheet(item: $book) { book in<br>            NavigationStack {<br>                UpsertView(book: book)<br>                    .environment(\.modelContext, book.modelContext!)<br>            }<br>        }<br>    }<br>}</pre><p>No need to think about it anymore!</p><p>Of course, all of this depends on your implementation , whether you have a dedicated router, or use navigationDestination(for: ) instead of sheets. SwiftUI gives us plenty of tools to make life easier and fully embrace its <strong>declarative nature</strong>. I’m sure you’ll find something that fits your project perfectly.</p><h3>Conclusion</h3><p>I hope this article helped you get a clearer picture of SwiftData — both its foundations and the trickier, more subtle details that can be hard to wrap your head around.</p><p>It’s been a real pleasure to share the thought process that led me to this final result. There were a few somewhat redundant steps along the way, but I really wanted to present it exactly as I thought it through in the moment.</p><p>If I had to sum up this architecture, it would come down to these key ideas:</p><ul><li><strong>Objects carry their own context</strong></li></ul><p>I rely heavily on the persistentItem.modelContext property that lets you check whether an object has a context, and it’s a key part of our checks and overall workflow.</p><ul><li><strong>Views are logic-agnostic via Environment</strong></li></ul><p>Views don’t handle persistence directly. The environment override propagates behavior throughout the hierarchy, and you can keep using @Environment(\.modelContext) just like you normally would in SwiftData. No need to worry about any overly custom layers.</p><ul><li><strong>Rollback by non-action (fail-safe)</strong></li></ul><p>An isolated context with autosaveEnable = false ensures nothing is persisted by default. You must explicitly save, but in return, simply dismissing the view is enough to <strong>cancel everything</strong>.</p><ul><li><strong>A single view for creation and editing</strong></li></ul><p>The @Bindable + switch(for: ) pattern eliminates duplication. Same view, no boilerplate . The context takes care of the rest.</p><ul><li><strong>ModelContext extensions as an abstraction layer</strong></li></ul><p>Our goal isn’t to shove all the SwiftData logic into a view model. The framework is designed to work with the environment and its macros, so let’s leverage that. That said, we still don’t want to clutter our views with 15 lines of SwiftData business logic, so implementing a ModelContext extension tailored to our needs seems like an ideal solution.</p><p>I’d love to hear how you’ve approached similar challenges with SwiftData, maybe you’ve found another elegant way around these issues!</p><p>Thanks so much for reading, and happy coding! 💻</p><p>Mathis 🎸</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fd0cefd8d87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Redraw System In Depth: Attributes, Recomputation, Diffing and Observation.]]></title>
            <link>https://medium.com/@matgnt/swiftui-redraw-system-in-depth-attributes-recomputation-diffing-and-observation-66b469fdcada?source=rss-43a7c410e21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/66b469fdcada</guid>
            <category><![CDATA[views]]></category>
            <category><![CDATA[core-animation]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Mathis Gaignet]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 07:06:51 GMT</pubDate>
            <atom:updated>2025-12-09T15:51:04.774Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWYQoLCnnYZhtSr6tCxnrw.png" /></figure><h3>Introduction</h3><p>The arrival of SwiftUI in 2019 brought about a major shift in view management. Indeed, views in UIKit used classes with inheritance, particularly from UIViewController or UIView. Views were therefore retained throughout their entire lifecycle.</p><p>But with SwiftUI, views are structs that conform to the View protocol, thus reinforcing POP (Protocol Oriented Programming).</p><p>The big difference is that SwiftUI will use your struct to execute the body and… poof! It’s done, the struct is destroyed. This raises the question: if my view structs are constantly destroyed and recreated, how do I maintain state? I could try something like this:</p><pre>struct Birthday: View {<br>    var age = 10<br>    <br>    var body: some View {<br>        VStack {<br>            Button(&quot;Happy birthday!&quot;) {<br>                age += 1<br>            }<br>        }<br>    }<br>}</pre><p>But this won’t work, first because body itself is immutable, so Swift won’t let us do this and throws a compilation error, and more importantly, even if it were possible, it would serve no purpose since leaving and returning to the view creates a new instance, meaning our value would never persist.</p><p>SwiftUI therefore gives us the ability to have data persistence, even though the struct is destroyed and reconstructed frequently. And this tool is the @State property wrapper.</p><p>But how does all this work? We add this property wrapper and everything just works? Let’s explore the inner workings of data persistence in SwiftUI. This will help you truly understand how it functions and then adapt it to your needs to improve your app’s performance!</p><p>We’ll do this in 4 steps, since that’s how it happens internally:</p><ol><li>Invalidation (outdating) of attributes with dependency flagging</li><li>Body recomputation</li><li>Structural and content diffing</li><li>Intelligently redraws only what has changed</li></ol><p>We’ll also go further into certain characteristics of SwiftUI regarding its comparison system.</p><h3>State in SwiftUI</h3><p>For this, we first need to understand how state works in SwiftUI. This is a topic that can be quite complex given that the code is wrapped in PropertyWrappers, and we don’t fully know what’s happening under the hood unless we dig a bit deeper.</p><p>@State is an interface between SwiftUI’s storage system and your view.</p><p>On the view side, the two main things in the wrapper are the wrappedValue and the projectedValue. The first is simply the actual current value of the state. The second is a binding (get wrappedValue, set newValue) that is accessible with the ‘$’.</p><p>On the other side, @State will tell SwiftUI to manage the data persistence of this variable itself and will use attributes for that purpose. Inside a view, several attributes are created.</p><p>The most important ones are those created by the parent view if it needs to pass parameters to its subview that will receive the source of truth (the state). But for a view that declares its own state, each @State attribute is managed by the view itself during its first initialization. It remains there for the entire lifetime of the view, as long as its identity doesn’t change!</p><p>And this is an important detail — never do this:</p><pre>struct MusicBand: View {<br>    let name: String<br>    @State private var playSong = false<br>    <br>    var body: some View {<br>        VStack {<br>            Text(&quot;Band name is \(name)&quot;)<br>            Button(&quot;Play&quot;) {<br>                playSong.toggle()<br>            }<br>        }<br>    }<br>}<br><br>struct MyMusic: View {<br>    @State private var rockNRoll = false<br>    <br>    var body: some View {<br>        VStack {<br>            if rockNRoll {<br>                MusicBand(name: &quot;The Rolling Stones&quot;)<br>            } else {<br>                MusicBand(name: &quot;The Beatles&quot;) /* Different ID! */ <br>            }<br>        }<br>    }<br>}</pre><p>Here, you’re going to have a major identity problem with the MusicBand view, since it will lose its identity when rockNRoll becomes true, only to take on a new one. What happens? No data persistence occurs, and your @State private var playSong = false returns to its default value every time. A simple way to fix this is to use the ternary operator like this:</p><pre>struct MyMusic: View {<br>    @State private var rockNRoll = false<br>    <br>    var body: some View {<br>        VStack {<br>            MusicBand(name: rockNRoll ? &quot;The Rolling Stones&quot; : &quot;The Beatles&quot;) /* Same ID */<br>        }<br>    }<br>}</pre><p>Remember, in SwiftUI, all identities must be <strong>stable.</strong></p><h4>The Attributs System</h4><p>Let’s go back to this attribute. Its purpose is to hydrate your view template with the actual values.</p><p>The other attributes are created for the body, and for its content (which will need layout, spacing, etc.)</p><pre>struct Recompute: View {<br>    @State private var threshold: CGFloat = 50.0 /* &lt;- attribut created */<br>    <br>    var body: some View {<br>        VStack { /* &lt;- attribut created */<br>            Button(&quot;change&quot;) { /* &lt;- attribut created - on tap: transaction created */<br>                threshold = 41.24<br>            }<br>            Text(&quot;threshold is \(threshold)&quot;) /* attribut created - Using the value! */<br>        }<br>    }<br>}</pre><p>When I click on ‘change’, what Apple calls a <strong>transaction</strong> is created. Their definition is simple:</p><blockquote>It represents a change in the SwiftUI view hierarchy that must be performed before the next frame.</blockquote><p>This can contain a single state change, or a group. If an action changes 7 @State variables in your application, they will all be in this same transaction.</p><p>Then, it takes care of marking your state variable’s attribute as <strong>outdated (dirty)</strong>. This is followed by a cascade effect, where all attributes that depend on this state variable’s attribute are also marked as outdated. It’s just <strong>a flag</strong>, so it only takes a very short time to execute. Once completed, the state can update itself and through the same cascade effect as the flag, update all the dependencies that use it.</p><h4>Recomputing the bodies of structures</h4><p>When the @State value changes, its attribute is marked as outdated.</p><p>If your body actually reads that state (the wrappedValue), the body attribute becomes outdated as well and needs to be recomputed. To do this, SwiftUI reads the current view value coming from the parent, then creates a <strong>temporary copy</strong> of your view struct containing the updated state. It evaluates the body property on that temporary instance, stores the resulting view value, and discards the temporary copy. This process produces a new view tree, completing the recomputation.</p><p>Importantly, this only happens if your body <em>reads</em> the state. If SwiftUI detects that the updated wrappedValue is never accessed during body evaluation, it will simply <strong>skip the recomputation entirely.</strong></p><pre>struct MovieDetail: View {<br>    let movie: Movie<br>    @State private var favouriteMovies: [String] = []<br>    <br>    var body: some View {<br>        VStack {<br>            Button(&quot;Add as favourite&quot;) {<br>                favouriteMovies.append(movie.name)<br>            }<br>        }<br>    }<br>}</pre><p>Here, the state variable changes but is not used in the body. However, it’s not clear about who’s checking if the body uses it. Is there an analysis engine inside the transaction? Before it’s created? In any case, remember one thing: SwiftUI won’t bother recomputing your body if the state value is not used in it.</p><p>We can even go further by looking at the new SwiftUI tool in Instruments brought by Apple in 2025. It contains what they call an Effect Graph, which allows you to see in detail the behavior of body recomputation, particularly with the attributes and transactions we talked about</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*ZLK-psgyPw3sZD9zwLnGOw.png" /><figcaption>MovieDetail.body [skipped]</figcaption></figure><p>Careful, this works with this example because I’m only writing, but if you use something that needs a binding like a Slider, TextField or other, don’t forget that the binding is nothing other than a get set on the wrappedValue and therefore needs to read the actual value inside the body itself!</p><p>So, you will have body recomputations even if you “don’t read this value yourself.”</p><pre>struct MovieLibrary: View {<br>    @State private var collectionCompletion: CGFloat = 50.0<br>    <br>    var body: some View {<br>        let _ = Self._printChanges() /* MovieLibrary: _collectionCompletion changed. */<br>        VStack {<br>            Slider(value: $collectionCompletion, in: 0...100)<br>                .padding()<br>        }<br>    }<br>}</pre><p>The printChanges will trigger on each slide.</p><h4>Default Init Recomputation</h4><p>Even though you’re safe with computed properties, be careful not to initialize a stored property that would change every time, otherwise the body will be recomputed every time, for instance:</p><pre>struct MovieDetail: View {<br>    let movie: Movie<br>    @State private var favouriteMovies: [String] = []<br>    <br>    var body: some View {<br>        VStack {<br>            ReleaseDateInfos()<br>        }<br>        .toolbar {<br>            ToolbarItem(placement: .topBarLeading) {<br>                Button(&quot;Add as favourite&quot;) {<br>                    favouriteMovies.append(movie.name)<br>                }<br>            }<br>        }<br>    }<br>}<br><br>struct ReleaseDateInfos: View {<br>    let today = Date()<br>    var body: some View {<br>        let _ = Self._printChanges() /* ReleaseDateInfos: @self changed. */<br>        /* ... */<br>    }<br>}</pre><h4>Reading the wrappedValue</h4><p>Ok and now what happens if we read a wrappedValue in the body? SwiftUI will understand that our body does indeed depend on this state value and will choose to recompute it. But it’s smart, since my subviews (Artwork, Synopsis, Reviews) have no dependencies on this value in their own body. They won’t be recomputed.</p><pre>struct MovieDetail: View {<br>    let movie: Movie<br>    @State private var favouriteMovies: [String] = []<br>    <br>    var body: some View {<br>        VStack {<br>            HStack {<br>                Text(movie.name)<br>                Image(systemName: favouriteMovies.contains(movie.name) ? &quot;star.fill&quot; : &quot;star&quot;)<br>            }<br>            Artwork()<br>            Synopsis()<br>            Reviews()<br>        }<br>        .toolbar {<br>            ToolbarItem(placement: .topBarLeading) {<br>                Button(&quot;Add as favourite&quot;) {<br>                    favouriteMovies.append(movie.name)<br>                }<br>            }<br>        }<br>    }<br>}<br><br>struct Artwork: View {<br>    var body: some View {<br>        /* ... */<br>    }<br>}<br><br>struct Synopsis: View {<br>    var body: some View {<br>        /* ... */<br>    }<br>}<br><br>struct Reviews: View {<br>    var body: some View {<br>       /* ... */<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*6qOIfMRIHXfCaLW-BtMuiQ.png" /></figure><p>As you can see, everything except my subviews is recomputed. And remember this for the rest of this article , <strong>only my extracted subviews are spared</strong>, my HStack containing the Text and Image, and the ToolbarItem are also marked as dirty and therefore recomputed.</p><p>Obviously, as soon as one of them has a dependency on this state value and uses it, its body will also be called</p><pre>struct MovieDetail: View {<br>    let movie: Movie<br>    @State private var favouriteMovies: [String] = []<br>    <br>    var body: some View {<br>        VStack {<br>            HStack {<br>                Text(movie.name)<br>                Image(systemName: favouriteMovies.contains(movie.name) ? &quot;star.fill&quot; : &quot;star&quot;)<br>            }<br>            Artwork(favouriteMovies: favouriteMovies)<br>            Synopsis()<br>            Reviews()<br>        }<br>        .toolbar {<br>            ToolbarItem(placement: .topBarLeading) {<br>                Button(&quot;Add as favourite&quot;) {<br>                    favouriteMovies.append(movie.name)<br>                }<br>            }<br>        }<br>    }<br>}<br><br>struct Artwork: View {<br>    let favouriteMovies: [String]<br>    <br>    var body: some View {<br>        if !favouriteMovies.isEmpty {<br>            /* ... */<br>        }<br>        /* ... */<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*EcHsF0FsG1T2xftw2lXS_A.png" /><figcaption>Artwork.body is called</figcaption></figure><h4>State Struct</h4><p>We’ve seen examples with a state value, but what about state types?</p><pre>struct Peru {<br>    var capital: String = &quot;Lima&quot;<br>    var population: Int = 34_000_000<br>}<br><br>struct Country: View {<br>    @State private var peru = Peru()<br>    <br>    var body: some View {<br>        let _ = Self._printChanges() /* Country: _threshold changed. */<br>        VStack {<br>            Button(&quot;Enlarge the city&quot;) {<br>                peru.population += 100<br>            }<br>            Text(&quot;Peru&#39;s capital is \(peru.capital)&quot;)<br>        }<br>    }<br>}</pre><p>I’m not reading the population property that I’m changing, and yet my body recomputes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B7-dEl0izg40qDGwxInxgw.png" /></figure><p>In fact, SwiftUI doesn’t do individual tracking of your struct’s properties. It tracks at the entire @Stateobject level.</p><blockquote>Your @State variable is used in the body and the struct changes? Ok, I’ll recompute it, I don’t care which property you access.</blockquote><p>The behavior is the same for a class. We’ll go into more detail about them at the end of this story.</p><p>We learned how the effect graph in Instruments proves invaluable for identifying performance bottlenecks caused by unnecessary view recomputation. Apple also calls this the “Dependency Graph” during WWDC 21 and illustrates it with this image that might help you see things even more clearly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WmWuofIe_8ZXGUDOWvg-7g.png" /><figcaption>The Dependency Graph</figcaption></figure><p>I quote:</p><blockquote>This structure is important because it allows SwiftUI to efficiently update only those views that require a new body. […] The secret of the graph is that if the dependency changes, only those views will be invalidated. […] SwiftUI will call each view’s body, producing a new body value for each view. […] That may result in more dependencies changing, but not always! Because views are value types, SwiftUI can efficiently compare them to only update the right subset of views.</blockquote><p>In fact, both the Effect Graph and the Dependency Graph are user-friendly names that actually refer to the private <strong>AttributeGraph</strong> <strong>framework</strong>, which is therefore responsible for tracking dependencies and handling the invalidation cascade.</p><p>If you want to dive deeper, I recommend Rens Breur’s articles on <a href="https://rensbr.eu/blog/swiftui-attribute-graph/">AttributeGraph</a> and <a href="https://rensbr.eu/blog/swiftui-diffing/">diffing algorithm</a>. They explain how to print the graph in lldb, the different types of view graphs, and offer a very in-depth look at the internals of the entire system.</p><p>Anyhow, this explanation validates our observations that SwiftUI only recomputes the bodies that depend on the state value. And in the process, it compares the views between them to determine what subset of views are worth updating. Could this be the famous diffing everyone talks about? We’ll dive deeper into that later, but first, let’s explore more about body recomputation; there’s still plenty to uncover!</p><h4>Equatable</h4><p>It’s also possible to influence the body recomputation behavior with the Equatable protocol. Indeed, it’s possible to give SwiftUI our own constraints, and tell it for example that it’s not necessary to recompute FlightDetail’s body if the flightNumber hasn’t changed.</p><pre>struct Airport: View {<br>    @State private var flightNumber = 1857<br>    @State private var isDelayed = false<br>    <br>    var body: some View {<br>        VStack {<br>            Button(&quot;Delay toggle&quot;) {<br>                isDelayed.toggle()<br>            }<br>            FlightDetail(flightNumber: flightNumber, isDelayed: isDelayed)<br>        }<br>    }<br>}<br><br>struct FlightDetail: View, Equatable {<br>    let flightNumber: Int<br>    let isDelayed: Bool<br>    <br>    static func == (lhs: Self, rhs: Self) -&gt; Bool {<br>        lhs.flightNumber == rhs.flightNumber<br>    }<br>    <br>    var body: some View {<br>        let _ = Self._printChanges() /* Printing each time */<br>        <br>        VStack {<br>            Text(&quot;Your flight number is \(flightNumber)&quot;)<br>            Text(isDelayed ? &quot;Your plane is delayed&quot; : &quot;Your plane is on time&quot;)<br>        }<br>    }<br>}</pre><p>The problem is that… it doesn’t work 🤔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCElcCTqeynDisntsqnSEQ.png" /><figcaption>FlightDetail.body is called each time</figcaption></figure><p>My body recomputes every time I toggle this isDelayed, even though I’m asking Equatable to recompute this body only if the flightNumber changes.</p><p>The cause of this behavior lies in a somewhat obscure Swift function named _isPOD(). Let’s look at its definition in the documentation:</p><pre>func _isPOD&lt;T&gt;(_ type: T.Type) -&gt; Bool where T : ~Copyable, T : ~Escapable</pre><blockquote>A type is <em>trivial</em>, also known as POD (“plain ol’ data”), if it merely stores data and has no extra copy, move, or destruction semantics. Trivial objects can be copied by replicating their bits, and are destroyed through deallocation. A type is trivial only if all data members are also trivial.</blockquote><p>And from Xcode we have a simplified version:</p><blockquote>A POD type is a type that does not require any special handling on copying or destruction.</blockquote><p>This means that my struct, which only contains an int variable and a bool variable, is POD. Let’s check this out:</p><pre>let _ = print(_isPOD(FlightDetail.self)) /* true */</pre><p>Ok, and what’s the point of knowing this? Well, Apple engineer John Harper explains it perfectly in a tweet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*soVKPt9XF6AEloRK4Cg4Aw.png" /></figure><p>Ok, so basically, Swift doesn’t bother calling our == since it assumes that our == implementation will probably be equivalent to a field-by-field comparison.</p><pre>// What Swift thinks<br>struct isPOD: Equatable {<br>    var count: Int<br>    var flag: Bool<br>    <br>    static func == (lhs: Self, rhs: Self) -&gt; Bool {<br>        lhs.count == rhs.count &amp;&amp; lhs.flag == rhs.flag<br>    }<br>}</pre><p>And they’re not wrong! The examples I’m using to illustrate this behavior are not realistic at all, but are there to be understandable.</p><p>But then, how do we force it to evaluate my ==? Well, John Harper also answered us in this tweet: We need to tell the parent view that this view is an EquatableView.</p><p>Two ways to do this:</p><pre>EquatableView(content: FlightDetail(flightNumber: flightNumber, isDelayed: isDelayed))<br><br>/* OR */ <br><br>FlightDetail(flightNumber: flightNumber, isDelayed: isDelayed)<br>    .equatable()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*avlI_KxPTQ9MPDC06K5rTw.png" /><figcaption>First tap: Checking the EquatableView and recomputing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*3oYE9Hn3jLFT_g9X__NpPg.png" /><figcaption>Second tap and more: It’s Equatable -&gt; Don’t recompute</figcaption></figure><p>Now, as soon as the flightNumber is equal to the old one, my body won’t be recomputed because my equatable is respected — the flightNumber is <strong>identical</strong>. As I told you, the example is silly because doing this prevents me from knowing if my plane is delayed! But it’s important to understand this concept so you won’t be surprised if you have to deal with this behavior.</p><p>So, what about views with isPOD = false? Well, according to John, it prefers to first check our own Equatable implementation, then fallback to its own field comparison if it doesn’t find one.</p><p>So, let’s add a String variable to our FlightDetail. Indeed, String uses Copy On Write and therefore invalidates the isPOD definition:</p><blockquote>..and has no extra copy […] does not require any special handling on copying.</blockquote><pre>struct Airport: View {<br>    @State private var flightNumber = 1857<br>    @State private var isDelayed = false<br>    @State private var planeType = &quot;Boeing 777&quot;<br>    <br>    var body: some View {<br>        VStack {<br>            Button(&quot;Delay toggle&quot;) {<br>                isDelayed.toggle()<br>            }<br>            FlightDetail(flightNumber: flightNumber, isDelayed: isDelayed, planeType: planeType)<br>        }<br>    }<br>}<br><br>struct FlightDetail: View, Equatable {<br>    let flightNumber: Int<br>    let isDelayed: Bool<br>    let planeType: String<br>    <br>    static func == (lhs: Self, rhs: Self) -&gt; Bool {<br>        lhs.flightNumber == rhs.flightNumber<br>    }<br>    <br>    var body: some View {<br>        let _ = Self._printChanges()<br>        let _ = print(_isPOD(FlightDetail.self))<br>        <br>        VStack {<br>            Text(&quot;Your flight number is \(flightNumber)&quot;)<br>            Text(isDelayed ? &quot;Your plane is delayed&quot; : &quot;Your plane is on time&quot;)<br>        }<br>    }<br>}</pre><p>And as expected, the flight detail’s body doesn’t recompute, without even needing to use EquatableView or .equatable().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*O4GgOjiBr1oDXa5-RlyNdw.png" /><figcaption>No EquatableView, just like if my FlightDetail view didn’t have any dependencies on this state.</figcaption></figure><p>This behavior is completely understandable, given that if a view takes a custom type as a parameter, it wouldn’t be unreasonable to think that we’d want to set comparison constraints on certain parameters used in the view instead of tracking the whole type.</p><p>Even though now, with the new observation system, such granularity is handled for us.</p><h3>Observation</h3><p>As you know, it’s common to need to observe a class, whether it’s your view model, something you want to put in the environment…</p><p>For this, you use either Combine’s observation system (ObservableObject + @Published), or SwiftUI’s new one with the @Observable macro. These two systems work somewhat differently and would require an entire article on their observation system, but I’ll roughly explain how this impacts our body recomputation.</p><h4>Combine</h4><p>The Combine system works as follows: After conforming your class to ObservableObject, which is nothing more than a protocol, SwiftUI will be able to subscribe to objectWillChange. You initiate the source of truth from your view with @StateObject, and the properties published with @Published will persist.</p><pre>/// The type of publisher that emits before the object has changed.<br>associatedtype ObjectWillChangePublisher : Publisher = ObservableObjectPublisher where Self.ObjectWillChangePublisher.Failure == Never<br><br>/// A publisher that emits before the object has changed.<br>var objectWillChange: Self.ObjectWillChangePublisher { get }</pre><p>You remember our transactions triggered when a @State changes in our views? Even if we change multiple @State variables, they will all be flagged in this same transaction. And in the same way, this is why Combine uses objectWillChange and not objectDidChange. It needs to know that it WILL change in order to coalesce every change into a single update.</p><pre>cancellable = john.objectWillChange<br>    .sink { _ in<br>        print(&quot;\(john.age) will change&quot;)<br>}</pre><p>However, as soon as there’s an established dependency between the view and the object (via @StateObject or @ObservedObject), no matter which property of that object is accessed, it will recompute your body.</p><p>Let’s take a look at this exemple:</p><pre>final class ObservedClass: ObservableObject {<br>    @Published var phoneNumber = 5124845954<br>    @Published var phoneModel = &quot;11 Pro&quot;<br>    @Published var batteryLevel = 45<br>    @Published var isDeveloper = true<br>}<br><br>struct Recompute: View {<br>    @StateObject private var observedClass = ObservedClass()<br>    <br>    var body: some View {<br> <br>        VStack {<br>            Button(&quot;Toggle developer mode&quot;) {<br>                observedClass.isDeveloper.toggle()<br>            }<br>            HardwareDetails(observedClass: observedClass)<br>            SoftwareDetails(observedClass: observedClass)<br>        }<br>    }<br>}<br><br>struct HardwareDetails: View {<br>    @ObservedObject var observedClass: ObservedClass<br>    <br>    var body: some View {<br>        let _ = Self._printChanges() /* HardwareDetails: _observedClass changed. */<br>        Text(&quot;Phone model is \(observedClass.phoneModel) with a remaining battery percentage of \(observedClass.batteryLevel)&quot;)<br>    }<br>}<br><br>struct SoftwareDetails: View {<br>    @ObservedObject var observedClass: ObservedClass<br>    <br>    var body: some View {<br>        let _ = Self._printChanges() /* SoftwareDetails: _observedClass changed. */<br>        Text(&quot;The user has the number \(observedClass.phoneNumber) and is \(observedClass.isDeveloper ? &quot;a&quot; : &quot;not a&quot;) developer&quot;)<br>    }<br>}</pre><p>Here, I modify the isDeveloper property which is only used in SoftwareDetails. But the simple fact of accessing another property of this same object somewhere else (HardwareDetails), triggers a recompute of its view body. As you’ll have understood, this system allows subscribing to and publishing changes, but without granularity. Here, the whole _observedClass has changed, like the print shows.</p><h4>Observable</h4><p>And that’s why Apple introduced the new observation system with @Observable at WWDC 23. It fixes the old problem of excessive body recomputation. I won’t go into the details of how it works, but overall, it uses an engine that provides storage for tracking and data access called the ObservationRegistrar.</p><p>This structure has 4 main functions:</p><ul><li>Access (allows access to the data)</li><li>willSet (works roughly like Combine API’s objectWillChange)</li><li>didSet (Called after the value has changed)</li><li>withMutation (which is basically a get set)</li></ul><p>The particularity of these functions is that they take a KeyPath as a parameter, which will be one of the key for more granularity and to avoid unnecessary body recomputation.</p><p>If we now migrate to the new observation method <a href="https://developer.apple.com/documentation/swiftui/migrating-from-the-observable-object-protocol-to-the-observable-macro">as Apple demonstrates</a>, only the view’s body that contains the isDeveloper property will be recomputed.</p><p>As a result, sharing the entire object in its subviews becomes less constraining than with the old method. My print now shows that only the property of the object has changed.</p><pre>@Observable<br>final class ObservedClass {<br>    var phoneNumber = 5124845954<br>    var phoneModel = &quot;11 Pro&quot;<br>    var batteryLevel = 45<br>    var isDeveloper = true<br>}<br><br>struct Recompute: View {<br>    @State private var observedClass = ObservedClass()<br>    <br>    var body: some View {<br> <br>        VStack {<br>            Button(&quot;Toggle developer mode&quot;) {<br>                observedClass.isDeveloper.toggle()<br>            }<br>            HardwareDetails(observedClass: observedClass)<br>            SoftwareDetails(observedClass: observedClass)<br>        }<br>    }<br>}<br><br>struct HardwareDetails: View {<br>    let observedClass: ObservedClass<br>    <br>    var body: some View {<br>        let _ = Self._printChanges()<br>        Text(&quot;Phone model is \(observedClass.phoneModel) with a remaining battery percentage of \(observedClass.batteryLevel)&quot;)<br>    }<br>}<br><br>struct SoftwareDetails: View {<br>    let observedClass: ObservedClass<br>    <br>    var body: some View {<br>        let _ = Self._printChanges() /* SoftwareDetails: \ObservedClass.isDeveloper changed. */<br>        Text(&quot;The user has the number \(observedClass.phoneNumber) and is \(observedClass.isDeveloper ? &quot;a&quot; : &quot;not a&quot;) developer&quot;)<br>    }<br>}</pre><p>If you want to go further in comparing these two observation systems, I recommend <a href="https://medium.com/@michaellong/the-observation-is-more-efficient-myth-e58c1e1d62da">this article by Michael Long</a>.</p><p>Note that trying to influence body recomputation with Equatable when using observation won’t work.</p><pre>struct HardwareDetails: View, Equatable {<br>    @ObservedObject var observedClass: ObservedClass<br>    <br>    static func == (lhs: Self, rhs: Self) -&gt; Bool {<br>        lhs.observedClass.phoneModel == rhs.observedClass.phoneModel &amp;&amp;<br>        lhs.observedClass.batteryLevel == rhs.observedClass.batteryLevel<br>    }<br>    <br>    var body: some View {<br>        let _ = Self._printChanges() /* HardwareDetails: _observedClass changed. */<br>        let _ = print(_isPOD(HardwareDetails.self)) /* false */<br>        Text(&quot;Phone model is \(observedClass.phoneModel) with a remaining battery percentage of \(observedClass.batteryLevel)&quot;)<br>    }<br>}</pre><h3>Diffing</h3><p>Well, there we have it. We’ve covered everything there is to know about body recomputation. But we still have one Apple quote to dig into:</p><blockquote>Because views are value types, SwiftUI can efficiently compare them to only update the right subset of views.</blockquote><p>So Apple would compare views against each other to redraw only the right subset of views on screen… The thing is, we haven’t seen any comparison logic so far, it was mostly about dependencies between the body and state.</p><p>On top of that, like we saw with our MovieDetail, if our body is recomputed, only the subviews that have no dependency on this state are spared from the process. All other elements in the view that aren’t extracted are marked as dirty and recomputed.</p><p>This could lead us to think that there’s simply no diffing, and therefore no performance difference between subviews that are recomputed as a ‘side effect’, and those that are recomputed because they depend on a state.</p><p>Well… there are differences.</p><p>And while they’re visible with the same SwiftUI Instruments in the “Other Updates” section, it’s mainly with the Core Animation Activity tool that it becomes really obvious.</p><p>Let’s take this view as an exemple.</p><pre>struct Airport: View {<br>    @State private var isDelayed = false<br>    var body: some View {<br>        VStack {<br>            FlightDetail(isDelayed: isDelayed)<br>            List(0...1000, id: \.self) { number in<br>                Text(number.description)<br>            }<br>        }<br>        .toolbar {<br>            ToolbarItem {<br>                Button(&quot;Delay toggle&quot;) {<br>                    isDelayed.toggle()<br>                }<br>            }<br>        }<br>    }<br>}<br><br>struct FlightDetail: View {<br>    let isDelayed: Bool<br>    var body: some View {<br>        Text(isDelayed ? &quot;Your plane is delayed&quot; : &quot;Your plane is on time&quot;)<br>    }<br>}</pre><p>I think you now know the expected behavior. I change my isDelayed, and it’s used by a subview. This will recompute my body, and that of the subview. And, just as we said before, it will also recompute my List.body as a ‘side effect’ as shown here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*Pc6VlIbmQfeiNiEDuGa1Sg.png" /><figcaption>List.body and ToolbarItem are called</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*mQdnlZHMDkCD64ipv9BZrw.png" /><figcaption>Core Animation takes 6.84ms to redraw and have 412 commits.</figcaption></figure><p>Now, if I make it so that my list has a real dependency on my state, by adding 1 to the number if isDelayed = true like this:</p><pre>struct Airport: View {<br>    @State private var isDelayed = false<br>    var body: some View {<br>        VStack {<br>            FlightDetail(isDelayed: isDelayed)<br>            List(0...1000, id: \.self) { number in<br>                Text(isDelayed ? (number + 1).description : number.description)<br>            }<br>        }<br>        .toolbar {<br>            ToolbarItem {<br>                Button(&quot;Delay toggle&quot;) {<br>                    isDelayed.toggle()<br>                }<br>            }<br>        }<br>    }<br>}<br><br>struct FlightDetail: View {<br>    let isDelayed: Bool<br>    var body: some View {<br>        Text(isDelayed ? &quot;Your plane is delayed&quot; : &quot;Your plane is on time&quot;)<br>    }<br>}</pre><p>The effect graph will be strictly the same, however, Core Animation does more than double the work here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*zzIF8UE1U1CyiSQNwvO-hQ.png" /><figcaption>Core Animation takes 14.12ms to redraw and have 505 commits.</figcaption></figure><p>And SwiftUI “Other Updates” shows us how the Text content inside that list is updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NfjPud5mDgWTTQJhdiFepg.png" /><figcaption>With no dependency on the list</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Udivy6yM0gd6h-lHoA4isg.png" /><figcaption>With dependency on the list</figcaption></figure><p>This proves that SwiftUI knows this List hasn’t actually changed, even if it’s marked dirty, so it keeps the old one. All this, even though there’s no notable difference between the two effect graphs of the two scenarios.</p><p>But don’t use this as an excuse to stop breaking your views into separate structs! 😏</p><p>Well, my example remains simple to facilitate understanding, but what you need to remember is that you shouldn’t panic when seeing all these recomputations in the effect graph, since SwiftUI will optimize behind the scenes for the real differences between the two changes.</p><p><em>PS: Note that I’m using a simple List here; the results will be quite different with a LazyVStack!</em></p><h3>Conclusion</h3><p>We now understand what SwiftUI hides behind its property wrappers and recomputation , redraw system. This knowledge allows us to make informed architectural decisions and leverage the new Instruments tools, like the SwiftUI instrument with its precise Effect Graph.</p><p>Understanding these internals transforms SwiftUI from a “magic” framework into a predictable system where we can optimize performance and debug issues with confidence.</p><p>I really enjoyed digging into this! If you want to go further, don’t hesitate to run your own tests with Xcode, and feel free to drop a little 👏 if you enjoyed this story 😊</p><h4>Sources</h4><p><a href="https://developer.apple.com/videos/play/wwdc2019/226">WWDC 19</a></p><p><a href="https://developer.apple.com/videos/play/wwdc2020/10040">WWDC 20</a></p><p><a href="https://developer.apple.com/videos/play/wwdc2021/10022">WWDC 21</a></p><p><a href="https://developer.apple.com/videos/play/wwdc2025/306">WWDC 25</a></p><p><a href="https://www.donnywals.com/understanding-how-and-when-swiftui-decides-to-redraw-views/">Donny Wals Article</a></p><p>My own tests on Xcode &amp; Instruments</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66b469fdcada" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Swift 6.2 Concurrency: A Complete Tutorial]]></title>
            <link>https://medium.com/@matgnt/mastering-swift-6-2-concurrency-a-complete-tutorial-99a939b0f53b?source=rss-43a7c410e21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/99a939b0f53b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Mathis Gaignet]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 20:58:34 GMT</pubDate>
            <atom:updated>2025-11-16T04:33:02.613Z</atom:updated>
            <content:encoded><![CDATA[<h3>QMastering Swift 6.2 Concurrency: A Complete Tutorial</h3><h3>Introduction</h3><p>Swift Concurrency has become a cornerstone of multi-threading in SwiftUI. As the successor to GCD, it was unveiled during WWDC21. Apple has continuously improved concurrency over time, introducing more performant TaskGroups, better performance optimizations, and task priorities. However, it wasn’t until Swift 6.0 that concurrency received its major overhaul with strict concurrency, Region Based Isolation, and a better data race safety.</p><p>Less than a year after its arrival, Apple announced Swift 6.2 at WWDC25, bringing its own set of innovations, notably “Default Actor Isolation” that automatically isolates all our types on the MainActor, and the new nonsending keyword for nonisolated methods.</p><p>During my SwiftUI learning journey, I became fascinated by Swift Concurrency. On one hand, I was completely lost; the concepts seemed overwhelming. On the other hand, I wanted to dive deep into the documentation, watch WWDC videos, and really understand how everything worked under the hood. And this is exactly why I want to share this article with you.</p><p>So make yourself a coffee, I’ll cover the fundamentals of Swift concurrency and gradually integrate the latest Swift 6.2 features.</p><p>Swift supports multi-threading through various mechanisms. When multiple threads are used, each one maintains its own stack (call stack for function execution), while they all share access to heap (memory space for objects) managed by ARC. Thread number 1, called the main thread, is the one used by default by the compiler when you declare a function in Swift without using any concurrency.</p><pre>func someComputation() {<br>    // Main Thread<br>}</pre><p>This is also the thread used to update our application’s UI, as the compiler refuses UI updates from global threads. The problem is that if this thread serves both UI updates and business logic calculations, it can become saturated. This manifests in our application as freezes, which we call hangs. To solve this, we need to first spot them through Instruments, and reproduce them. Then, we can introduce Swift Concurrency.</p><h3>Async/Await</h3><p>Before diving in, it’s crucial to understand the principle of isolation. In Swift Concurrency, your code runs either in an isolated context (actor) or in a non-isolated context. Until the arrival of Swift 6.2 in 2025, every created type was nonisolated by default (except the views). This means creating a class and declaring a synchronous method inside it would run <strong>on the caller’s thread</strong> (so, on the MainThread if you’re not using any concurrency). Declaring an asynchronous method would automatically run on a random background thread from the global pool, known as the globalConcurrentExecutor (GCE).. And honestly, it makes sense:</p><blockquote>“synchronous = main, asynchronous = background thread”.</blockquote><p>But first, what is an actor, and what is this isolation for? Well, when our code is isolated to a specific actor, it will be queued through what’s called a SerialExecutor. So even if you call two functions simultaneously that both modify the same property, there’s no risk of a data race.</p><p>Executors are the pieces of Swift’s concurrency runtime that manage how and where asynchronous tasks are executed. Actor isolation is about which context’s state code is allowed to access. The fact that an executor in an actor is called SerialExecutor is to show that this executor will serialise the jobs, queuing them one by one. Together, the SerialExecutor (runtime mechanism) and actor isolation (compile-time checking) provide Swift’s data-race safety guarantee.</p><p><em>PS: It’s possible to create your own custom </em><em>SerialExecutor and use it in Tasks outside the actor using the new </em><em>TaskExecutor introduced with iOS 18</em></p><p>Let’s start with the non-isolated code. To declare an asynchronous method, we need the first keyword of Swift Concurrency: async. As mentioned earlier, the method is now asynchronous and its body runs on the GCE (globalConcurrentExecutor).</p><pre>class Model {<br>    func fetchingData() async {<br>        /* A random background thread (GCE) */<br>    }<br>}</pre><p>The second important keyword is await. It serves multiple purposes, but its main role is acting as a <strong>potential</strong> suspension point. Any method annotated with async must be called with await. This is a syntactic requirement that marks potential suspension points in our code.</p><pre>class Model {<br>   func fetchingDataCaller() async {<br>       /* 1. John - a random background thread from the GCE */<br>       await fetchingData()<br>       /* 4. Back into the same thread as the third one */<br>   }<br>   <br>   func fetchingData() async {<br>       /* 2. John thread */<br>       do {<br>           let url = URL(string: /* some URL */)!<br>           let (data, _) = try await URLSession.shared.data(from: url)<br>           /* 3. Another thread - could be John, or a new one */<br>       } catch {<br>           print(&quot;Error: \(error)&quot;)<br>       }<br>   }<br>}</pre><p>In the case of the GCE, the Swift runtime will be optimized if there is no actual suspension point, as is the case here.</p><pre>class Model {<br>    func heavyComputationCaller() async {<br>        /* John - a random background thread from the GCE */<br>        let _ = await heavyComputation()<br>        /* Back into the method as John thread */<br>    }<br>    <br>    func heavyComputation() async -&gt; Int {<br>        /* John thread */<br>        var result = 0<br>        <br>         for i in 1...100_000 {<br>             let temp = i % 1000<br>             result = (result + temp * temp) % Int.max<br>             <br>             var n = i % 1000 + 1<br>             var steps = 0<br>             while n != 1 &amp;&amp; steps &lt; 100 {<br>                 if n % 2 == 0 {<br>                     n = n / 2<br>                 } else {<br>                     n = n * 3 + 1<br>                 }<br>                 steps += 1<br>             }<br>             result = (result + steps) % Int.max<br>         }<br>         <br>         var numbers = Array(1...5_000).shuffled()<br>         for i in 0..&lt;min(numbers.count, 1000) {<br>             for j in 0..&lt;(min(numbers.count, 1000) - i - 1) {<br>                 if numbers[j] &gt; numbers[j + 1] {<br>                     numbers.swapAt(j, j + 1)<br>                 }<br>             }<br>         }<br>        /* John thread */<br>         return result % Int.max<br>    }<br>}</pre><p>Note that a synchronous function like the one at the beginning of this post executes according to its caller’s thread. So by default, it will always be on the main thread, but if called from an asynchronous method that itself isn’t isolated, or a Task.detached, then it will run on the GCE as well!</p><p>But this information isn’t necessarily critical. While it’s important to understand GCE distribution, what interests us is MainActor isolation, which we’ll use extensively to update our UI and avoid data races. So what we want is to do our heavy calculations on the GCE and return to the main thread to update the UI.</p><p>For this, we need to isolate either our entire type or our method. Very often, we’ll use View Models, Presenters, or Interactors — regardless of their name, their purpose is simple: update the UI with their observation system. We’ll simplify by annotating our entire class with @MainActor like this:</p><pre>@MainActor @Observable<br>class Model {<br>    func asynchronousIsolated() async {<br>        /* Main Thread -&gt; some UI updates */<br>    }<br>}</pre><p>Now, all methods in this class will inherit from the Main Actor and therefore run on the main thread.</p><p>In our example above with our @MainActor annotated class, we still have the option to remove one of the methods from this MainActor isolation by making it nonisolated. This gives us something like this:</p><pre>@MainActor<br>class Model {<br>    func asynchronousIsolated() async {<br>        /* Always main thread */<br>    }<br>    <br>    nonisolated<br>    func asynchronousNonIsolated() async {<br>        /* Always on the GCE */<br>    }<br>    <br>    func synchronousIsolated() {<br>        /* Always main thread */<br>    }<br>    <br>    nonisolated<br>    func synchronousNonIsolated() {<br>        /* Depends on where you call it */<br>    }<br>}<br></pre><p>Finally, remember I said await serves on multiple purpose. One of them is to cross actor’s boundaries, even on synchronous methods.</p><pre>@MainActor @Observable<br>class WeatherManager {<br>    let service = WeatherService.shared<br>    var currentWeather: Forecast&lt;DayWeather&gt;?<br>    <br>    func fetchWeather() async throws {<br>        currentWeather = try await service.weather(for: .paris).dailyForecast<br>    }<br>    <br>    func averageTemp() -&gt; Double {<br>        guard let today = currentWeather?.first else { return 0.0 }<br>        <br>        let highCelsius = today.highTemperature.converted(to: .celsius).value<br>        let lowCelsius = today.lowTemperature.converted(to: .celsius).value<br>              <br>        return (highCelsius + lowCelsius) / 2<br>    }<br>}<br><br>class Model {<br>    let manager = WeatherManager()<br>    <br>    func isItColdToday() async -&gt; Bool {<br>        if await manager.averageTemp() &lt; 0 { /* Crossing actor’s boundaries */<br>            return true<br>        } else {<br>            return false<br>        }<br>    }<br>}</pre><p>Here, I must await my averageTemp() function even though it’s synchronous, because I’m changing isolation. I’m calling a function isolated to the main actor, from a non-isolated instance.</p><p>For this, your type (WeatherManager in this example) must be Sendable.</p><p>Keep in mind that a class with mutable properties that doesn’t need to observe changes will typically become an actor (like a cache, for example). An actor, as mentioned above, works the same way as the MainActor, so with a SerialExecutor. But it won’t ever run on the main thread. So, as you’ve probably understood, the main difference between an actor and a non-isolated async function is that the actor’s GCE will be serialized, whereas the non-isolated async function’s GCE will not. And of course, the actor provides us with isolation.</p><h4>Actor’s Reentrancy</h4><p>Actors, however, have a drawback. Remember, their SerialExecutor executes only one job at a time. Think of it like this: you’re standing in a line at a cinema for the last ticket to a sold-out show. The cashier (our Swift actor) can only serve one person at a time (SerialExecutor).</p><p>Now, imagine that the cashier first checks how many tickets are left when a new person approaches, and then verifies their ID. If there’s an issue, they ask the person to go to another counter that handles the ID verification, and then come back to their own counter once it’s done. (you have an await function that exit the actor and goes somewhere else) So they tell you:</p><blockquote>Go check your ID at one of the verification desks, then come back.</blockquote><p>At that moment, <strong>the cashier is free to serve the next person in line.</strong></p><p>Here’s where the problem happens:</p><ul><li>Person 1 arrives. The cashier sees 1 ticket left and asks them to verify their ID.</li><li>Person 2 arrives. The cashier sees 1 ticket left and asks them to also verify their ID.</li></ul><p>Both think they’re entitled to the same last ticket! When they come back from ID verification:</p><ul><li>Person 1 buys the ticket: stock goes to 0</li><li>Person 2 buys the ticket: stock goes to -1</li></ul><p>Suddenly, we’ve sold the same ticket twice. This is exactly what happens with actor reentrancy in Swift: if you await inside an actor method, other tasks can sneak in during the suspension, potentially messing with shared state.</p><p>There are two ways to fix it:</p><ul><li>Check the stock after the wait:</li></ul><p>Person 2 would come back, see there’s no ticket left, and politely get told: “Sorry, sold out.” Simple, but the second person waits for nothing.</p><ul><li>Handle everything at the same counter</li></ul><p>The cashier verified the ID without sending you elsewhere. Now no one else can sneak in while you’re in the process.</p><p>In Swift 6, the second solution works as follows:</p><pre>actor ImageProcessor {<br>    let imageLoader = ImageLoader()<br>    var processedImages: [UIImage] = []<br>    <br>    func loadAndProcessImage() async {<br>        await imageLoader.fetchFromDisk()  // No suspension point!<br>        await applyFilters()<br>    }<br>    <br>    func applyFilters() async {...}<br>}<br><br>class ImageLoader {<br>    func fetchFromDisk(isolation: isolated (any Actor)? = #isolation) async {<br>        // Inherit ImageProcessor&#39;s SerialExecutor and isolation<br>    }<br>}</pre><p>Even though imageLoader.fetchFromDisk() is preceded by await, this is only a syntactic requirement. There is actually no suspension point because imageLoader.fetchFromDisk() remains isolated and runs on the same executor as ImageProcessor. As a result, applyFilters() will only execute after imageLoader.fetchFromDisk() has finished running, instead of starting as soon as the await is reached.</p><p>If we go back to our analogy, loadAndProcessImage() (our cashier) will run fetchFromDisk() on <strong>ImageProcessor</strong> <strong>SerialExecutor</strong> (the same counter) thanks to the isolation parameter.</p><p>To learn more about the Inheritance of Actor Isolation, check out <a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0420-inheritance-of-actor-isolation.md">the Swift Evolution 0420</a>.</p><h3>Strict concurrency</h3><p>I won’t go through all the Swift 6 changes, particularly those that are already outdated in Swift 6.2. If you’ve been using global variables or singletons, beware that the Swift 6 compiler won’t have your back. However, with the arrival of default actor isolation, which we’ll explore later in this post , this issue will already be resolved.</p><pre>// ... is not concurrency-safe because it is nonisolated global shared mutable state<br>var globalCounter = 0 <br>static var shared = MyManager()  </pre><h3>Closure Capture — sending vs @Sendable</h3><p>Now that I’ve reminded you of the basics, let’s dive into closure capture. Swift 6 has also introduced the new sending keyword, replacing @Sendable in many cases, like in this Task.</p><pre>public init(priority: TaskPriority? = nil, operation: sending @escaping @isolated(any) () async -&gt; Success)</pre><p>To put it simply:</p><ul><li>@Sendable = The <strong>type</strong> must be thread-safe (immutable / Sendable)</li><li>sending = The <strong>value</strong> must be in a disconnected region at the moment of the transfer</li></ul><p>In Swift 5.9, capturing non-Sendable types in Task closures was resulting in an error:</p><pre>class MapManager {<br>    var response: MKLocalSearch.Response?<br>}<br><br>class MapModel {<br>    func getResponse() {<br>        let manager = MapManager()<br>        Task {<br>            manager.response = await Helper.searchPlaces() /* Error in 5.9!! */<br>        }<br>    }<br>}</pre><p>Swift 6 fixes this through <strong>Region-Based Isolation</strong> (<a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0414-region-based-isolation.md">Swift Evolution 0414</a>) and the sending keyword (<a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0420-inheritance-of-actor-isolation.md">Swift Evolution 0420</a>).</p><p>RBI is a mechanism that allows the Swift compiler to safely determine when a non-Sendable value can be transferred between isolation domains (such as actors or tasks) without risk of concurrency issues, by analyzing the isolation regions where the values are used.</p><p>The compiler now checks:</p><p>Is manager used after creating the Task? If not, the transfer is safe:</p><pre>func getResponse() {<br>    let manager = MapManager()<br>    Task {<br>        manager.response = await Helper.searchPlaces()  // OK in Swift 6<br>    }<br>    // Compiles: manager is never used here<br>}</pre><p>If it is used once again, a compiler error is thrown.</p><pre>class MapManager {<br>    var response: MKLocalSearch.Response?<br>}<br><br>class MapModel {<br>    func getResponse() {<br>        let manager = MapManager()<br>        Task {<br>            manager.response = await Helper.searchPlaces()<br>        }<br>        manager.response = nil /* &lt;- I&#39;m reusing it elsewhere! */<br>    }<br>}<br>// No longer works in any case.</pre><p>The same logic applies to actor boundaries. This code now works:</p><pre>class VinylRecord {<br>    init(title: String, artist: String) {…}<br>}<br><br>actor VinylStore {<br>    func addRecord(_ record: VinylRecord) {<br>        collection.append(record)<br>    }<br>}<br><br>func addNewVinyl(title: String, artist: String) async {<br>    let record = VinylRecord(title: title, artist: artist)<br>    // Regions: [(record)]  ← record is in a disconnected region<br>    await VinylStore.shared.addRecord(record)<br>    // Regions: [{(record), VinylStore.shared}]  ← record is now in the actor&#39;s region<br>}</pre><p><strong>The key</strong>: Swift 6 performs flow-sensitive analysis to ensure non-Sendable values are transferred safely, without requiring you to mark everything as @Sendable.</p><h3>Swift 6.2: Default Actor Isolation</h3><p>If I’m showing you all these examples, it’s not without reason. With the arrival of Swift 6.2, every new project created in Xcode 26 will have a new setting enabled: ‘Default Actor Isolation’ set to ‘MainActor’. This means that all the types we create in our project will automatically inherit from the Main Actor, without us needing to explicitly add it. And what’s the connection with the Sendable examples just before? Well, it’s simple: the Sendable protocol is automatically inferred when a type is declared as @MainActor.</p><p>And if we think about it carefully, a large part of our application can run in single-thread (main thread) without needing to resort to concurrency, especially if your app doesn’t have much computation. As long as your code executes quickly, there won’t be any issues! Plus, thanks to this mode, Swift will protect your code from any potential data races. If we go back to our network call example, we’ll have this behavior:</p><pre>class Model {<br>   func fetchingDataCaller() async {<br>       /* Main thread */<br>       await fetchingData()<br>       /* Back into the main thread */<br>   }<br>   <br>   func fetchingData() async {<br>       /* Main thread */<br>       do {<br>           let url = URL(string: /* some URL */)!<br>           let (data, _) = try await URLSession.shared.data(from: url) /* &lt;---- Apple offloads this work on a background thread for us */<br>           /* Main thread */<br>       } catch {<br>           print(&quot;Error: \(error)&quot;)<br>       }<br>   }<br>}</pre><p>You can see that now, all methods run on the main thread, except when we encounter the await from Apple’s URLSession API. And that’s great because it’s precisely this part of the code that could take the most time. We therefore only have the strict minimum running in the GCE, without being surprised by any asynchronous behavior we might have encountered before enabling this setting. This is exactly what Apple wants: minimise data races as much as possible. If you want to know more about Apple’s vision, watch <a href="https://developer.apple.com/videos/play/wwdc2025/268/">Embracing Swift Concurrency from WWDC 25.</a></p><p><em>PS: To avoid any concurrency issues, when you assign ‘Default Actor Isolation’ to MainActor, remember to do it for all your targets, as well as on your different SPMs if you have any.</em></p><pre>.target(<br>    name: &quot;A SPM from your project&quot;,<br>    swiftSettings: [<br>        .defaultIsolation(MainActor.self)<br>    ]<br>)</pre><p>However, we haven’t seen yet how to force a method to run on the GCE with this new setting. You might have certain methods that will perform a lot of work and need to be “manually” moved to a background thread.</p><p>At first glance, after following my previous examples, we might think that to switch to the GCE with this new setting, we just need to declare a method identical to asynchronousNonIsolated(). We saw that, even if the class is isolated to the actor, making this method asynchronous and non-isolated allowed it to always run in the GCE.</p><p>And you’re absolutely right! However, Apple unveiled a new macro: @concurrent. Annotating a function with this macro will always make it run on the GCE, just like asynchronousNonIsolated().</p><p>So what’s the difference? That’s what I wondered for a few hours, before discovering the introduction of a new keyword: nonsending.</p><pre>class Model {<br>    func asynchronousIsolated() async {<br>        /* Always main thread */<br>    }<br>    <br>    nonisolated(nonsending)<br>    func asynchronousNonIsolated() async {<br>        /* Depends on where you call it */<br>    }<br>    <br>    func synchronousIsolated() {<br>        /* Always main thread */<br>    }<br>    <br>    nonisolated<br>    func synchronousNonIsolated() {<br>        /* Depends on where you call it */<br>    }<br><br>    @concurrent<br>    func concurrentMethod() {<br>        /* Always on the GCE */<br>    }<br>}</pre><p>With this new keyword, the asynchronousNonIsolated() method acts the same way as a synchronousNonIsolated(), meaning it inherits the context of its caller.</p><p>And not only does it do that, but remember that line of code used to force a function’s isolation on an actor to avoid unnecessary hops (suspension points) and reentrancy issues?</p><pre>(isolation: isolated (any Actor)? = #isolation)</pre><p>Well, with nonisolated(nonsending), that’s now inferred automatically!</p><p>Fortunately, a second new setting is also introduced: “nonisolated nonsending by default”, which is part of the new “Approachable Concurrency”. With this setting, the nonsending keyword is automatically inferred when we annotate a method as nonisolated.</p><p>To learn more about nonisolated async and executor switching, you can <a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0461-async-function-isolation.md">read the Swift Evolution 0461</a>.</p><p>So we don&#39;t need to add it manually. From now on, my examples will use this mode.</p><h4>Current Recommendations and Settings</h4><p>At the time I’m writing these lines, a few weeks after WWDC25, Apple encourages us to use Default Actor Isolation as MainActor, as well as “nonisolated nonsending by default” set to “Yes”. However, the latter is set to “No” for every new project created in Xcode 26. If you want to conform to Apple’s recommendation, you’ll need to enable it manually. Perhaps it will automatically be set to “Yes” later.</p><p>Note that the 2 settings are completely dissociable, so it’s possible to enable “nonisolated nonsending by default” while having a project not isolated to MainActor. In this case, all your methods declared in a created type, and therefore non-isolated, will inherit from the caller! I don’t see use cases where such usage would be beneficial, especially since every new project is already isolated to MainActor as I mentioned, so I’ll continue this article with Apple’s recommended settings. If you want to deep dive into these 2 settings, there’s <a href="https://juniperphoton.substack.com/p/wwdc-25-notes-game-of-identifying?r=1ss9aj&amp;utm_campaign=post&amp;utm_medium=web&amp;triedRedirect=true">an awesome article from Juniperphoton.</a></p><p>In any case, with now these 2 settings enabled, the only way now to move a function to the GCE for all use cases is @concurrent.</p><p>Now that you’re familiar with the new features and how they work, can you deduce where these methods from the ConcurrentThread class will run?</p><pre>struct MainMaster: View {<br>    var body: some View {<br>        VStack {<br>            Text(&quot;Main Master&quot;)<br>        }<br>        .task {<br>            Task.detached {<br>                let model = ConcurrentThread()<br>                await model.firstMethod()<br>            }<br>        }<br>    }<br>}<br><br>class ConcurrentThread {<br>    func firstMethod() async {<br>        await secondMethod()<br>        await thirdMethod()<br>    }<br>    <br>    @concurrent<br>    func secondMethod() async {<br>        try? await Task.sleep(for: .seconds(1))<br>        await thirdMethod()<br>    }<br>    <br>    nonisolated<br>    func thirdMethod() async {...}<br>}</pre><p>Let’s break down what happens step by step. The first method to be called is firstMethod(). It&#39;s isolated to the main actor (default actor isolation) and called from within a Task.detached. This detached task doesn&#39;t change anything to our firstMethod() since it isn&#39;t marked as nonisolated, it still runs on the main thread. Nonetheless, it creates a hop that we don’t want, so don’t do that.</p><p>When we hit the first await, the main thread’s executor is released (so it can work on other jobs) and secondMethod() begins execution. Since it&#39;s annotated with @concurrent, it runs on the GCE. After Task.sleep, the thread may change, so it&#39;s possibly a different random background thread from the GCE that takes over.</p><p>Then thirdMethod() is called from within secondMethod(). Since it&#39;s annotated as nonisolated (nonsending by default), it will be called from the same executor and thread as its caller, so it runs on the same background thread as secondMethod() from the GCE.</p><p>Once all of this completes, our initial await secondMethod() call wakes up and tells us it has finished its work. We&#39;re back in firstMethod(), which means we&#39;re back on the main thread’s executor. Then thirdMethod() is called again! But this time, from the main thread. Just like before, it inherits the executor and the thread from its caller, but now that caller is the main thread, so it will run on the main thread’s executor and Thread 1.</p><p>Now you understand why we often say that await “releases the main thread”. When the parent method runs on the main thread and awaits a method that runs in the background, it will release the executor of the main thread, do its work in the background (on the GCE), and then return to the main thread to update the UI without any issues!</p><p>Note that we’re already dealing with an uncommon scenario here, since we’re using @concurrent, which is a resource that&#39;s only necessary when you have your own business logic that needs to run on the GCE, either to avoid basic hangs or to address other performance issues.</p><h4>Synchronous @Sendable closures</h4><p>We’ve talked earlier about @Sendable VS sending.There is one problem you could still encounter. This is about synchronous @Sendable closure.</p><p>SwiftUI and other Apple frameworks sometimes use synchronous @Sendableclosures (particularly on @preconcurrency), either for expensive calculations and performance concerns, or to work in a thread-safe manner.</p><p>Let’s take for example this Label closure annotated with @Sendable in the PhotosPicker from PhotosUI.</p><p>As a brief reminder of this keyword, it indicates that the closure’s content must only contain Sendable types.</p><pre>@preconcurrency nonisolated public init(selection: Binding&lt;PhotosPickerItem?&gt;, matching filter: PHPickerFilter? = nil, preferredItemEncoding: PhotosPickerItem.EncodingDisambiguationPolicy = .automatic, @ViewBuilder label: @Sendable () -&gt; Label)</pre><pre>@Observable<br>class Model {<br>    func imageDataToUI(_ cocktail: Cocktail) -&gt; UIImage? {<br>        guard let data = cocktail.imageData else { return nil }<br>        return UIImage(data: data)<br>    }<br>}<br><br>struct PickerView: View {<br>    @State private var model = Model()<br>    @State private var pickerItem: PhotosPickerItem?<br>    let cocktail: Cocktail<br>    <br>    var body: some View {<br>        VStack {<br>            PhotosPicker(selection: $pickerItem) {<br>                if let image = model.imageDataToUI(cocktail) {<br>                 // Main actor-isolated property &#39;model&#39; can not be referenced from a Sendable closure<br>                    Image(uiImage: image)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Here, you’ll notice a compiler error:</p><blockquote>Main actor-isolated property ‘model’ can not be referenced from a Sendable closure</blockquote><p>Followed by:</p><blockquote>Call to main actor-isolated instance method ‘imageDataToUI’ in a synchronous nonisolated context</blockquote><p>Apple covers this example in<a href="https://developer.apple.com/videos/play/wwdc2025/266/"> WWDC 25: Explore Concurrency in SwiftUI</a> with this code below:</p><pre>struct SchemeContentView: View {<br>    let isLoading: Bool<br>    @State private var pulse = false<br>    <br>    var body: some View {<br>        Text(isLoading ? &quot;Please wait&quot; : &quot;Extract&quot;)<br>            .visualEffect { content, _ in<br>                content<br>                    .blur(radius: pulse ? 2 : 0)<br>                    // Main actor-isolated property &#39;pulse&#39; can not be referenced from a Sendable closure<br>            }<br>    }<br>}</pre><p>They state:</p><blockquote>So really, Swift is warning us about the attempt to access the pulse property. Of course, we know that as a member of the View, pulse is @MainActor isolated. So the compiler is telling me, even though I can send self in here, accessing is @MainActor isolated property pulse is unsafe.</blockquote><p>But this isn’t really correct, and easily verifiable, since this code compiles:</p><pre>struct SchemeContentView: View {<br>    let isLoading: Bool<br>    var pulse = false<br>    <br>    var body: some View {<br>        Text(isLoading ? &quot;Please wait&quot; : &quot;Extract&quot;)<br>            .visualEffect { content, _ in<br>                content<br>                    .blur(radius: pulse ? 2 : 0)<br>            }<br>    }<br>}</pre><p>The difference is that I’m not using @Stateon my pulse property. Yet, it’s still isolated to the main actor! This behavior is very well explained in this <a href="https://fatbobman.com/en/posts/why-certain-view-modifiers-in-swift-6-cannot-usethe-state-property/">excellent article by Fatbobman</a>.</p><p>As you know, @State is just a property wrapper that simplifies our lives, but under the hood it generates code equivalent to this:</p><pre>private var _model = State(wrappedValue: model)<br>var model: Model {<br>    get { _model.wrappedValue }<br>    set { _model.wrappedValue = newValue }<br>}</pre><p>This effectively means we’re calling the getter like this:</p><pre>PhotosPicker(selection: $model.pickerItem) {<br>    if let image = model.getter().imageDataToUI(cocktail) {<br>        // ...<br>    }<br>}</pre><p>The issue is that <strong>this getter is not </strong><strong>@Sendable</strong>! Even though it’s @MainActor, synchronous @Sendable closures are forbidden from calling @MainActor methods. This is easily verifiable.</p><pre>struct PickerView: View {<br>    @State private var pickerItem: PhotosPickerItem?<br>    <br>    var body: some View {<br>        VStack {<br>            PhotosPicker(selection: $pickerItem) {<br>                if let image = isolatedMethod() { <br>                    /* Call to main actor-isolated instance method &#39;isolatedMethod()&#39; <br>                       in a synchronous nonisolated context */<br>                    image<br>                }<br>            }<br>        }<br>    }<br>    func isolatedMethod() -&gt; Image? {<br>        return Image(&quot;Image&quot;)<br>    }<br>}</pre><p>The reason is simple: even though our method will always run on the main thread, it’s being called from within a @Sendable closure that can execute on any thread. This would cause the current thread to block while waiting! Since Swift doesn’t infer await in synchronous closures, the error becomes logical.</p><h4>Solutions</h4><p>Apple offers us 2 solutions in their WWDC video.</p><blockquote>I can make a copy of the pulse variable in the closure’s capture list, and refer to the copy instead. This way, I’m no longer sending self into this closure.</blockquote><p>Once again, the problem isn’t sending self into the closure, since removing @State allows us to use self.pulse as we saw just before. However, this is the right solution to adopt, because it evaluates the @State getter <strong>before</strong> entering the closure.</p><pre>struct SchemeContentView: View {<br>    let isLoading: Bool<br>    @State private var pulse = false<br>    <br>    var body: some View {<br>        Text(isLoading ? &quot;Please wait&quot; : &quot;Extract&quot;)<br>            .visualEffect { [pulse] content, _ in<br>                content<br>                    .blur(radius: pulse ? 2 : 0)<br>            }<br>    }<br>}</pre><p>The second is this:</p><blockquote>Another strategy to make this work is to make everything we’re reading nonisolated.</blockquote><p>But this solution will in no way solve our @State getter problem. Let’s go back to our original example:</p><pre>@Observable<br>class Model {<br>    nonisolated func imageDataToUI(_ cocktail: Cocktail) -&gt; UIImage? {<br>        guard let data = cocktail.imageData else { return nil }<br>        return UIImage(data: data)<br>    }<br>}<br><br>struct PickerView: View {<br>    @State private var model = Model()<br>    @State private var pickerItem: PhotosPickerItem?<br>    let cocktail: Cocktail<br>    <br>    var body: some View {<br>        VStack {<br>            PhotosPicker(selection: $pickerItem) {<br>                if let image = model.imageDataToUI(cocktail) {<br>                // Main actor-isolated property &#39;model&#39; can not be referenced from a Sendable closure<br>                    Image(uiImage: image)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>I’ve annotated my imageToDataUI function with the nonisolated keyword as the solution suggests, and this therefore satisfies the compiler error:</p><blockquote>Call to main actor-isolated instance method ‘imageDataToUI’ in a synchronous nonisolated context</blockquote><p>Nevertheless, I still have the 2nd compilation error! Which, in the same way, can be resolved by removing @State.</p><pre>@State private var model = Model() -&gt; let model = Model()</pre><h4>Conclusion</h4><p>Apple oversimplifies in their WWDC explanation. The real problem is not the @MainActor isolation of the View&#39;s properties, but the fact that @State getter is not Sendable.</p><p>The recommended solution remains the capture [property], which evaluates the getter before entering the synchronous @Sendable closure.</p><h3>How does Apple want us to use concurrency?</h3><h4>Structured Concurrency</h4><p>Let’s illustrate this example with structured concurrency. You don’t need to annotate your group.addTask as @concurrentsince they’re already running on the GCE by default. Same goes for the MusicKit APIs in the example below. However, some methods can be resource-intensive here.</p><pre>class StructuredConcurrency {<br>    var albums: [Album] = []<br>  <br>    func fetchAlbums() async throws {<br>        try await checkAuthorizationStatus()<br>        var request = MusicLibraryRequest&lt;Album&gt;()<br>        let response = try await request.response()<br>        albums =  Array(response.items)<br>    }<br>    <br>    private func checkAuthorizationStatus() async throws { ... }<br>    <br>    func processAlbums() async throws {<br>        await withThrowingTaskGroup(of: AlbumProcessingResult?.self) { group in<br>            for album in self.albums {<br>                group.addTask {<br>                    try Task.checkCancellation()<br>                    <br>                    async let mapItems = self.findNearbyMusicVenues(for: album.recordLabelName)<br>                    async let images = self.processArtwork(for: album.artwork)<br>                    async let spotifySuccess = self.transferPlaylistToSpotify(for: album.appearsOn)<br>                    <br>                    var audioFormat: AVAudioFormat? = nil<br>                    if album.audioVariants?.contains(.dolbyAtmos) == true {<br>                        async let bedConfig = self.extractBEDChannelConfiguration(from: album)<br>                        audioFormat = try await bedConfig<br>                    }<br>                    <br>                    try Task.checkCancellation()<br>                    <br>                    return AlbumProcessingResult(<br>                        albumTitle: album.title,<br>                        nearbyVenues: try await mapItems,<br>                        processedImages: try await images,<br>                        spotifyTransferSuccess: try await spotifySuccess,<br>                        dolbyAtmosFormat: audioFormat,<br>                        videoAssets: []<br>                    )<br>                }<br>            }<br>            for await result in group { ... }<br>        }<br>    }</pre><p>To retrieve my map items in the first method should be fine, I’m using the MapKit API. But for processing the images, I’m having a lot of hang issues and we can see our main thread is working heavily on CoreGraphics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*AVBoOE1-wE7WOt39-omwjA.png" /><figcaption>Main thread is working hard!</figcaption></figure><p>Let’s add @Concurrent on our processArtwork method.</p><pre>@concurrent<br>private func processArtwork(for artwork: Artwork?) async throws -&gt; [UIImage] { ... }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*tQvxXtwGSgnPsixyfBX_mw.png" /><figcaption>Main thread is not saturated anymore</figcaption></figure><p>Boom! My UI is not glitchy anymore and I can scroll while fetching the datas!</p><h3>Conclusion</h3><p>Swift 6.2 marks a pivotal moment in the evolution of Swift Concurrency. With the introduction of “Default Actor Isolation” and “nonisolated nonsending by default” mode, Apple dramatically simplifies Swift Concurrency adoption by making development more predictable and safe by default.</p><p>Most of you code can now stay on the main thread &amp; be sendable. Your code is also protected against data races with zero additional effort. Actors reentrancies are significantly reduces, as well as unnecessary hops. And finally, use @concurrent only when you truly need it!</p><p>This approach finally addresses the main criticism of Swift Concurrency: its adoption complexity. By inverting the logic (main thread by default, GCE on demand), Apple makes concurrency accessible to all developers, not just experts.</p><p>That’s a wrap!</p><p>Swift 6.2 Concurrency might seem daunting, but remember: start with the main thread, add @concurrentonly when needed, and let Apple’s new defaults handle the rest.</p><p>Thanks for reading, and happy Swift coding ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99a939b0f53b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep dive into dynamic SwiftData queries]]></title>
            <link>https://medium.com/@matgnt/deep-dive-into-dynamic-swiftdata-queries-9d029568dd8f?source=rss-43a7c410e21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d029568dd8f</guid>
            <category><![CDATA[query]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mathis Gaignet]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 20:48:43 GMT</pubDate>
            <atom:updated>2025-07-19T08:58:34.426Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>SwiftData is a powerful framework that enables seamless data persistence, whether using the default container or connecting to your own backend through the DataStore introduced last year.</p><p>To get started, you define your data structure annotated with @Model</p><pre>@Model<br>final class Vinyl {<br>    var artistName: String<br>    var title: String<br>    @Relationship(deleteRule: .cascade, inverse: \Track.vinyl)<br>    var tracks: [Track]<br>    var duration: TimeInterval<br>    var releaseDate: Date<br>    var artwork: Data?<br>    <br>    init(artistName: String, title: String, tracks: [Track], duration: TimeInterval, releaseDate: Date, artwork: Data? = nil) {<br>        self.artistName = artistName<br>        self.title = title<br>        self.tracks = tracks<br>        self.duration = duration<br>        self.releaseDate = releaseDate<br>        self.artwork = artwork<br>    }<br>}<br><br>@Model<br>final class Track {<br>    var title: String<br>    var duration: TimeInterval<br>    var genre: String<br>    <br>    var vinyl: Vinyl?<br>    <br>    init(title: String, duration: TimeInterval, genre: String, vinyl: Vinyl? = nil) {<br>        self.title = title<br>        self.duration = duration<br>        self.genre = genre<br>        self.vinyl = vinyl<br>    }<br>}</pre><p>Since @Model conforms to the Observable protocol under the hood, only classes can be annotated with it. Just as @State tracks an @Observable class and redraws the view when needed, @Query works in the same reactive way.</p><pre>struct VinylsView: View {<br>    @Query private var vinyls: [Vinyl]<br>    <br>    var body: some View {<br>        ForEach(vinyls) { vinyl in<br>            /* ... */<br>        }<br>    }<br>}</pre><p>By default, @Query fetches all records you’ve inserted into your container. But in real-world applications, you’ll want to sort and filter this data efficiently. Let’s explore how to master these techniques.</p><h3>The basics of sorting and filtering</h3><p>First, let’s examine the different parameters that @Query can accept by looking at its documentation.</p><pre>@attached(accessor) @attached(peer, names: prefixed(`_`)) <br>public macro Query&lt;Value, Element&gt;(<br>    filter: Predicate&lt;Element&gt;? = nil, <br>    sort keyPath: KeyPath&lt;Element, Value&gt;, <br>    order: SortOrder = .forward, <br>    transaction: Transaction? = nil<br>) = #externalMacro(module: &quot;SwiftDataMacros&quot;, type: &quot;QueryMacro&quot;) <br>where Value : Comparable, Element : PersistentModel</pre><p>We can see it takes a filter parameter of type Predicate, a sort parameter of type KeyPath, and an order parameter of type SortOrder. Finally, it also accepts a transaction parameter that controls whether changes trigger animations in SwiftUI (default is nil for automatic animations).</p><p>Let’s explore how to use these parameters effectively.</p><h4>Filtering</h4><p>A predicate is declared using the new #Predicate macro introduced with Swift 5.9.</p><pre>struct VinylsView: View {<br>    @Query(filter: #Predicate&lt;Vinyl&gt; { $0.duration &lt; 35*60 }) private var vinyls: [Vinyl]<br>    <br>    var body: some View {<br>        ForEach(vinyls) { vinyl in<br>            /* ... */<br>        }<br>    }<br>}</pre><p>Now, every call to the vinyls variable will only return vinyl records with a duration less than 35 minutes.</p><h4>Sorting &amp; Ordering</h4><p>Sorting works with a KeyPath, targeting our type that conforms to where Value: Comparable, Element: PersistentModel. My persistent element is the Vinyl model, and its artistName property is comparable:</p><pre>@Query(sort: \Vinyl.artistName) private var vinyls: [Vinyl]</pre><p>By default, the sort order is .forward, meaning smallest to largest, regardless of type. We can change this to reverse:</p><pre>@Query(sort: \Vinyl.artistName, order: .reverse) private var vinyls: [Vinyl]</pre><h4>Combining Both</h4><p>Obviously, we can combine everything for very precise results:</p><pre>@Query(<br>    filter: #Predicate&lt;Vinyl&gt; { $0.duration &lt; 35*60 }, <br>    sort: \Vinyl.artistName, <br>    order: .reverse<br>) private var vinyls: [Vinyl]</pre><p>Now, every call to this @Query will return only vinyl records under 35 minutes, sorted by artist name in reverse alphabetical order (since it’s of type String).</p><h3>FetchDescriptor</h3><p>FetchDescriptor is a type specific to SwiftData. Let’s take a look at its documentation.</p><pre>public struct FetchDescriptor&lt;T&gt; where T : PersistentModel {<br>    public var predicate: Predicate&lt;T&gt;?<br>    public var sortBy: [SortDescriptor&lt;T&gt;]<br>    public var fetchLimit: Int?<br>    /* ... */ <br>}</pre><p>This type describes the filtering and sorting criteria for persistent type. Here, sortBy is of type SortDescriptor, which encapsulated both the KeyPath and order, the same parameters our @Query takes!</p><p>This makes perfect sense because under the hood, this is exactly what our macro does.</p><p>When we write:</p><pre>@Query(<br>    filter: #Predicate&lt;Vinyl&gt; { $0.duration &lt; 35*60 }, <br>    sort: \Vinyl.artistName, <br>    order: .reverse<br>) private var vinyls: [Vinyl]</pre><p>Behind the scenes, the macro declares a FetchDescriptor with our parameters:</p><pre>FetchDescriptor(...)<br>context.fetch(descriptor)</pre><p>All of this is automatically done thanks to the Observable conformance.</p><p>We can therefore naturally move our filtering logic into external business logic outside our view.</p><pre>static func myDescriptor() -&gt; FetchDescriptor&lt;Vinyl&gt; {<br>    FetchDescriptor(<br>        predicate: #Predicate&lt;Vinyl&gt; { $0.duration &lt; 35*60 },<br>        sortBy: [SortDescriptor(\Vinyl.artistName, order: .reverse)]<br>    )<br>}<br><br>@Query(Vinyl.myDescriptor()) private var vinyls: [Vinyl]</pre><p>Note that sortBy is an array of SortDescriptor, allowing you to sort by multiple criteria:</p><pre>sortBy: [<br>    SortDescriptor(\Vinyl.artistName),<br>    SortDescriptor(\Vinyl.releaseDate, order: .reverse)<br>]</pre><h3>Static Filtering and Sorting limitations</h3><p>We’ve seen how to filter and sort our persisted data in our container using the different query parameters. However, this approach has some limitations: we’re sorting our data statically. It’s rare to have a view that needs such specific filtering throughout its entire lifecycle. Generally, we want to give users the ability to filter and sort their data themselves, whether through buttons, pickers, search bars, tags, etc.</p><p>We need to think about how to organize this @Query dynamically. There are two approaches for this.</p><h4>Without the query parameters</h4><p>This first approach consists of filtering the query data without using its parameters. Basically, we fetch the entire model and sort it afterward, just like we would with any array of data.</p><pre>enum FilterOptions: String, CaseIterable {<br>    case all = &quot;All&quot;<br>    case EP = &quot;EP&quot;<br>    case LP = &quot;LP&quot;<br>    case jazz = &quot;Jazz&quot;<br>    case thisYear = &quot;This Year&quot;<br>    <br>    func filteringLogic(_ vinyls: [Vinyl]) -&gt; [Vinyl] {<br>        switch self {<br>        case .all:<br>            return vinyls<br>        case .EP:<br>            return vinyls.filter { $0.duration &lt; 30*60 }<br>        case .LP:<br>            return vinyls.filter { $0.duration &gt; 30*60 }<br>        case .jazz:<br>            return vinyls.filter {<br>                $0.tracks.contains { $0.genre == &quot;Jazz&quot; }<br>            }<br>        case .thisYear:<br>            return vinyls.filter {<br>                $0.releaseDate &gt;= startOfYear &amp;&amp; $0.releaseDate &lt; endOfYear<br>            }<br>        }<br>    }<br>}<br><br>@Observable<br>final class Model {<br>    <br>    var selectedFilter: FilterOptions = .all<br>    <br>    func filteringQuery(_ vinyls: [Vinyl]) -&gt; [Vinyl] {<br>        selectedFilter.filteringLogic(vinyls)<br>    }<br>}<br><br>struct VinylsView: View {<br>    @State private var model = Model()<br>    @Query private var vinyls: [Vinyl]<br>    <br>    var body: some View {<br>        ForEach(model.filteringQuery(vinyls)) { vinyl in<br>            /* ... */<br>        }<br>    }<br>}</pre><p>And then we would have to do the same things for sorting items, and find a way to combine both into one function. This is not very intuitive.</p><h4>Using the query parameters intuitively</h4><p>The second solution is, in my opinion, the best. It allows us to use the query to its full advantage by making both sorting and filtering dynamic, as well as crafting a more logical approach and utilizes predicates. Indeed, they are generally more performant than the .filter methods we saw earlier, mainly because filtering happens at the database rather than in memory.</p><p>Let’s apply this method. First, we need to change our function. Let’s start with filtering. It should return a Predicate of our model. We’ll have this computed property:</p><pre>enum FilterOptions: String, CaseIterable {<br>    case all = &quot;All&quot;<br>    case EP = &quot;EP&quot;<br>    case LP = &quot;LP&quot;<br>    case jazz = &quot;Jazz&quot;<br>    case thisYear = &quot;This Year&quot;<br>      <br>    var filteringLogic: Predicate&lt;Vinyl&gt; {<br>        switch self {<br>        case .all:<br>            return #Predicate { _ in true }<br>        case .EP:<br>            return #Predicate { $0.duration &lt; 30*60 }<br>        case .LP:<br>            return #Predicate { $0.duration &gt; 30*60 }<br>        case .jazz:<br>            return #Predicate {<br>                $0.tracks.contains { $0.genre == &quot;Jazz&quot; }<br>            }<br>        case .thisYear:<br>            return #Predicate {<br>                $0.releaseDate &gt;= startOfYear &amp;&amp; $0.releaseDate &lt; endOfYear<br>            }<br>        }<br>    }<br>}</pre><p>Our filtering now happens at the database level, providing much better performance. Let’s continue with sorting, which will take an array of SortDescriptor.</p><pre>enum SortingOptions: String, CaseIterable {<br>    case title = &quot;Title&quot;<br>    case artistName = &quot;Artist Name&quot;<br>    case duration = &quot;Duration&quot;<br>    case releaseDate = &quot;Release Date&quot;<br>    <br>    var sortDescriptors: [SortDescriptor&lt;Vinyl&gt;] {<br>        switch self {<br>        case .title:<br>            [SortDescriptor(\Vinyl.title)]<br>        case .artistName:<br>            [SortDescriptor(\Vinyl.artistName)]<br>        case .duration:<br>            [SortDescriptor(\Vinyl.duration, order: .reverse)]<br>        case .releaseDate:<br>            [SortDescriptor(\Vinyl.releaseDate)]<br>        }<br>    }<br>}</pre><p>We now have our two elements needed for @Query. Let’s try to incorporate this into our view.</p><pre>@Observable<br>final class Model {<br>    var selectedFilter: FilterOptions = .all<br>    var selectedSorting: SortingOptions = .artistName<br>}<br><br>struct VinylsView: View {<br>    @State private var model = Model()<br>    @Query(filter: model.selectedFilter.filteringLogic, sort: model.selectedSorting.sortDescriptors) <br>    private var vinyls: [Vinyl]<br>    <br>    var body: some View {<br>        NavigationStack {<br>            List {<br>                ForEach(vinyls) { … }<br>            }<br>            .toolbar { … }<br>        }<br>    }<br>}</pre><p><strong>Problem: </strong>We can’t use the model instance this way, since it doesn’t exist yet. We’ll need to separate our vinyl displayer into another structure and integrate sorting and filtering directly from the init like this:</p><pre>struct VinylsView: View {<br>    @State private var model = Model()<br>    <br>    var body: some View {<br>        NavigationStack {<br>            List {<br>                VinylsList(selectedFilter: model.selectedFilter, selectedSorting: model.selectedSorting)<br>            }<br>            .toolbar { … }<br>        }<br>    }<br>}<br><br>struct VinylsList: View {<br>    @Query private var vinyls: [Vinyl]<br>    <br>    init(selectedFilter: FilterOptions, selectedSorting: SortingOptions) {<br>        _vinyls = Query(filter: selectedFilter.filteringLogic, sort: selectedSorting.sortDescriptors)<br>    }<br>    <br>    var body: some View {<br>        ForEach(vinyls) { … }<br>    }<br>}</pre><p>Perfect! We have dynamic filtering and sorting! The user can decide on filtering and sorting by modifying the selection variables in the Model! But we can go even further.</p><h3>Improvements</h3><p>I have a few filters and sorts in my example, but if I wanted to have all albums from each decade over the last 50 years, I would need to filter by releaseDate many more times, and therefore review all vinyl records sequentially for each query.</p><pre>enum FilterOptions: String, CaseIterable {<br>    /* ... */<br>    case sixties<br>    case seventies<br>    case eighties<br>    case nineties<br>    case thisYear<br>    /* ... */<br>}</pre><p>Imagine a collection of 10,000 vinyls records from the 80s, SwiftData must check the release of each of these records. Fortunately since WWDC24, Apple has brought us the new #Index tool. This tool allows SwiftData to create an optimized binary index, essential for searching in a table like this one. Instead of reviewing linearly, it uses a binary search algorithm.</p><p>To use it, I complete my Model like this:</p><pre>@Model<br>final class Vinyl {<br>    #Index&lt;Vinyl&gt;([\.releaseDate])<br>    <br>    var artistName: String<br>    var title: String<br>    @Relationship(deleteRule: .cascade, inverse: \Track.vinyl)<br>    var tracks: [Track]<br>    var duration: TimeInterval<br>    var releaseDate: Date<br>    var artwork: Data?<br>    <br>    init(artistName: String, title: String, tracks: [Track], duration: TimeInterval, releaseDate: Date, artwork: Data? = nil) {<br>        self.artistName = artistName<br>        self.title = title<br>        self.tracks = tracks<br>        self.duration = duration<br>        self.releaseDate = releaseDate<br>        self.artwork = artwork<br>    }<br>}</pre><p>We have therefore anticipated a first potential performance problem!</p><p>Secondly, we’re going to improve this sorting. Remember that a SortDescriptor is composed of a KeyPath and an order. We have only provided the KeyPath. It’s entirely possible to give the user the ability to reverse the order of their sorting very easily by passing a parameter!</p><p>Moreover, we can use the SortDescriptor array to our advantage to add chronological sorting on top of sorting by artist name, or even use it as prevention in case two albums have the same release date.</p><pre>enum SortingOptions: String, CaseIterable {<br>    case title = &quot;Title&quot;<br>    case artistName = &quot;Artist Name&quot;<br>    case duration = &quot;Duration&quot;<br>    case releaseDate = &quot;Release Date&quot;<br>    <br>    func sortDescriptors(reversed: Bool) -&gt; [SortDescriptor&lt;Vinyl&gt;] {<br>        let order: SortOrder = reversed ? .reverse : .forward<br>        <br>        switch self {<br>        case .title:<br>            return [<br>                SortDescriptor(\Vinyl.title, order: order)<br>            ]<br>        case .artistName:<br>            return [<br>                SortDescriptor(\Vinyl.artistName, order: order),<br>                SortDescriptor(\Vinyl.releaseDate, order: .forward)<br>            ]<br>            <br>        case .duration:<br>            return [<br>                SortDescriptor(\Vinyl.duration, order: order)<br>            ]<br>        case .releaseDate:<br>            return [<br>                SortDescriptor(\Vinyl.releaseDate, order: order),<br>                SortDescriptor(\Vinyl.artistName, order: .forward),<br>                SortDescriptor(\Vinyl.title, order: .forward)<br>            ]<br>        }<br>    }<br>}<br><br>@Observable<br>final class Model {<br>    /* … */<br>    var isReversed: Bool = false<br>}</pre><p>And there you go, just add a toggle in the view to manage the order as well.</p><pre>struct VinylsView: View {<br>    @State private var model = Model()<br>    <br>    var body: some View {<br>        NavigationStack {<br>            List {<br>                VinylsList(model: model, selectedFilter: model.selectedFilter, selectedSorting: model.selectedSorting)<br>            }<br>            .toolbar { … }<br>        }<br>    }<br>}<br><br>struct VinylsList: View {<br>    @Query private var vinyls: [Vinyl]<br>    let model: Model<br>    <br>    init(model: Model, selectedFilter: FilterOptions, selectedSorting: SortingOptions) {<br>        self.model = model<br>        <br>        _vinyls = Query(filter: selectedFilter.filteringLogic, sort: selectedSorting.sortDescriptors(reversed: model.isReversed))<br>    }<br>    <br>    var body: some View {<br>        ForEach(vinyls) { … }<br>    }<br>}</pre><p>Finally, you can see that it’s not necessarily very adequate to pass the filter, sort, and order in this @Query. But that’s where we can call upon FetchDescriptor again. Remember, it’s the type that @Query takes under the hood. First, it will be cleaner, and second, it will save us from passing all the enumerations.</p><pre>@Observable<br>final class Model {<br>    <br>    var selectedFilter: FilterOptions = .all<br>    var selectedSorting: SortingOptions = .artistName<br>    var isReversed: Bool = false<br>    <br>    <br>    var customFetchDescriptor: FetchDescriptor&lt;Vinyl&gt; {<br>        FetchDescriptor(predicate: selectedFilter.filteringLogic, sortBy: selectedSorting.sortDescriptors(reversed: isReversed))<br>    }<br>}<br><br>struct VinylsView: View {<br>    @State private var model = Model()<br>    <br>    var body: some View {<br>        NavigationStack {<br>            List {<br>                VinylsList(model: model)<br>            }<br>            .toolbar { … }<br>        }<br>    }<br>}<br><br>struct VinylsList: View {<br>    @Query private var vinyls: [Vinyl]<br>    let model: Model<br>    <br>    init(model: Model) {<br>        self.model = model<br>        <br>        _vinyls = Query(model.customFetchDescriptor)<br>    }<br>    <br>    var body: some View {<br>        ForEach(vinyls) { … }<br>    }<br>}</pre><p>And boom, with one line of code in our init, the user can filter, sort, and change the order of all their persisted data.</p><h4>Filtering or Sorting your enums</h4><p>There’s still an issue with this method that isn’t critical, but can be annoying if you’re not aware of it. You can’t use enums’ rawValue directly in sorting and filtering operations.</p><p>For example, if I want to add a condition property to my Vinyl model that indicates whether the record is mint, near mint, very good, etc., I won’t be able to use it directly in SortDescriptor or predicate operations.</p><p>Consider this code:</p><pre>@Model<br>final class Vinyl {<br>    /* Other properties .. */<br>    var condition: Condition<br>    <br>    init(condition: Condition = .mint) { ... }<br>}<br><br>enum Condition: String, Identifiable, Codable {<br>    case mint = &quot;Mint&quot;<br>    case nearMint = &quot;Near Mint&quot;<br>    case veryGood = &quot;Very Good&quot;<br>    case good = &quot;Good&quot;<br>    case fair = &quot;Fair&quot;<br>    case poor = &quot;Poor&quot;<br>    <br>    var id: String { self.rawValue }<br>}<br><br>enum SortingOptions: String, CaseIterable {<br>    /* Other sorting options */<br>    case condition = &quot;Condition&quot;<br>    <br>    var sortDescriptors: [SortDescriptor&lt;Vinyl&gt;] {<br>        switch self {<br>        case .condition:<br>            [SortDescriptor(\Vinyl.condition.rawValue)] /* &lt;- Error ! */<br>        }<br>    }<br>}<br></pre><p>First, you have to make your enum Codable for it to work with SwiftData. Then, the code compiles fine, but your app will crash when you try to select that particular filter, saying it doesn’t have a rawValue property. What’s happening is that you can’t directly use the enum’s rawValue, even indirectly.</p><p>I spent quite some time searching for solutions and trying various approaches. While there’s probably a better method out there, here’s what I found that works:</p><pre>@Model<br>final class Vinyl {<br>    /* Other properties */<br>    var condition: Condition<br>    var conditionValue: String<br>    <br>    init(condition: Condition = .mint, conditionValue: String = &quot;Mint&quot;) { ... }<br>}<br><br>struct SelectionView: View {<br>    @Bindable var vinyl: Vinyl<br>    <br>    var body: some View {<br>        VStack {<br>            Picker(&quot;Condition Selection&quot;, selection: $vinyl.condition) {<br>                ForEach(Condition.allCases) { condition in<br>                    Text(condition.rawValue).tag(condition)<br>                }<br>            }<br>            .onChange(of: vinyl.condition) { _, newValue in<br>                vinyl.conditionValue = newValue.rawValue<br>            }<br>        }<br>    }<br>}</pre><p>The solution is to create properties that only store the rawValue, and populate them using onChange on the picker that’s bound to the enum. I’d be really curious to see if any of you find a better solution!</p><h4>Search Bar</h4><p>I’ll finish with a search bar that will be managed dynamically with the @Query filter. For this, I’m going to declare a static function in my filtering enumeration, so that everything is in the same place.</p><pre>static func searchBar(_ searchText: String) -&gt; Predicate&lt;Vinyl&gt; {<br>    guard !searchText.isEmpty else {<br>        return #Predicate&lt;Vinyl&gt; { _ in true }<br>    }<br>    return #Predicate&lt;Vinyl&gt; {<br>        $0.title.contains(searchText) ||<br>        $0.artistName.contains(searchText)<br>    }<br>}<br><br>struct SearchVinyl: View {<br>    @Query private var vinyls: [Vinyl]<br>    @Bindable var model: Model<br>    <br>    init(model: Model) {<br>        self.model = model<br>        <br>        _vinyls = Query(filter: FilterOptions.searchBar(model.searchText))<br>    }<br>    <br>    var body: some View {<br>        NavigationStack {<br>            List(vinyls) { vinyl in<br>                Text(vinyl.artistName)<br>                Text(vinyl.title)<br>            }<br>            .searchable(text: $model.searchText)<br>        }<br>    }<br>}</pre><h3>Conclusion</h3><p>We have therefore seen in detail the different ways we can give users the ability to organize their persisted data. The use of Predicate and SortDescriptor , best practices with #Index and a dynamic search bar. I didn’t mention the #Expression macro, which can also be very useful when you need to compare non-boolean data. I encourage you to experiment with these techniques in your own projects; try combining multiple filters, test the performance with large datasets, and see how #Index improves your query speeds!</p><p>While I’ve tried to cover the essential patterns for dynamic SwiftData queries, there’s always room for improvement and different perspectives. If you spot any issues, have alternative approaches, or think something could be explained better, I’d love to hear from you in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d029568dd8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>