<?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 SwiftToday on Medium]]></title>
        <description><![CDATA[Stories by SwiftToday on Medium]]></description>
        <link>https://medium.com/@swifttoday?source=rss-8f60b87c00e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nKuCo99jTFH7M5pVtWoGew.jpeg</url>
            <title>Stories by SwiftToday on Medium</title>
            <link>https://medium.com/@swifttoday?source=rss-8f60b87c00e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:05:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swifttoday/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[Converting func value of type ‘@MainActor @Sendable (Notification) -> Void’ to ‘@Sendable…]]></title>
            <link>https://medium.com/@swifttoday/converting-func-value-of-type-mainactor-sendable-notification-void-to-sendable-2a223775e25d?source=rss-8f60b87c00e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a223775e25d</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[macos]]></category>
            <dc:creator><![CDATA[SwiftToday]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 18:56:55 GMT</pubDate>
            <atom:updated>2026-10-17T18:56:55.815Z</atom:updated>
            <content:encoded><![CDATA[<h3>Converting func value of type ‘@MainActor @Sendable (Notification) -&gt; Void’ to ‘@Sendable (Notification) -&gt; Void’ loses global MainActor</h3><p><strong>Swift • iOS &amp; macOS • Concurrency</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AW0XUnDiChnDeJJoJ39i5w.png" /></figure><blockquote><strong>TL;DR :</strong> Passing a main-actor-isolated method to NotificationCenter.addObserver(forName:object:queue:using:)fails in Swift 6 because the parameter expects a non-isolated @Sendable function. Don&#39;t strip the isolation with nonisolated. Pass an inline closure that captures self weakly and re-enters the main actor explicitly, with MainActor.assumeIsolated when you need the update to happen synchronously.</blockquote><h3>Where this error shows up</h3><p>The error appears when a Core Data controller observes store changes. The setup is common: a DataController that owns the NSPersistentContainer, and an observer that tells SwiftUI to refresh when the persistent store changes.</p><pre>@MainActor<br>class DataController: ObservableObject {<br>    let container: NSPersistentContainer<br><br>    init() {<br>        // ... container setup ...<br><br>        NotificationCenter.default.addObserver(<br>            forName: .NSPersistentStoreRemoteChange,<br>            object: container.persistentStoreCoordinator,<br>            queue: .main,<br>            using: remoteStoreChanged // ❌<br>        )<br>    }<br><br>    func remoteStoreChanged(_ notification: Notification) {<br>        objectWillChange.send()<br>    }<br>}</pre><p>This compiles quietly in Swift 5 mode with default settings. Under strict concurrency checking, or in Swift 6 language mode, it fails with:</p><pre>Converting function value of type &#39;@MainActor @Sendable (Notification) -&gt; Void&#39;<br>to &#39;@Sendable (Notification) -&gt; Void&#39; loses global actor &#39;MainActor&#39;</pre><p>The class doesn’t need an explicit @MainActor to trigger this. Projects built with a recent Xcode may use the <strong>Default Actor Isolation</strong> build setting (SE-0466, Swift 6.2), which makes every type in the module implicitly @MainActor.</p><h3>What the error means</h3><p>The compiler is comparing two function types:</p><pre>                 <strong>Type</strong>                           <strong>Isolation</strong><br>-----------------------------------------------------------------------------<br>What you pass :  <em>@MainActor @Sendable</em>           Guaranteed on the<br>                 <em>(Notification) -&gt; Void</em>         main actor<br>-----------------------------------------------------------------------------<br>What the API :   <em>@Sendable (Notification)</em>       No isolation: may be<br>accepts          <em>-&gt; Void</em>                        called from anywhere</pre><p>Your method promises that it only runs on the main actor, and the parameter type makes no such promise. Converting the first into the second would discard a guarantee the method depends on, so the compiler refuses.</p><p>The relevant part of the addObserver signature is:</p><pre>using block: @escaping @Sendable (Notification) -&gt; Void</pre><p>Two details make the mismatch unavoidable:</p><ol><li><strong>@Sendable doesn&#39;t imply an actor.</strong> It says a function is safe to call from concurrent contexts. It says nothing about <em>where</em> it runs. A @Sendable parameter without a global actor annotation is non-isolated.</li><li><strong>queue: .main is invisible to the type system.</strong> At runtime the block really is delivered on the main queue. The compiler has no way to connect an OperationQueue argument to MainActor isolation, so it can&#39;t verify the method&#39;s guarantee.</li></ol><p>(For background on isolation and Sendable, see the <a href="https://medium.com/@swifttoday/swift-concurrency-what-is-an-actor-and-when-should-you-use-one-ad857c0c06f1">earlier article on actors</a>.)</p><h3>A note on Swift versions</h3><p>@Sendable closures were introduced by SE-0302 in Swift 5.5. For years, passing a method reference like this produced no diagnostic at all, because concurrency checking was opt-in.</p><ul><li><strong>Swift 5 language mode, minimal checking:</strong> no diagnostic.</li><li><strong>Swift 5 language mode, strict concurrency checking enabled:</strong> warnings.</li><li><strong>Swift 6 language mode:</strong> errors.</li></ul><p>Projects that still build in Swift 5 mode may be hiding this problem rather than avoiding it.</p><h3>A related error: capturing a non-Sendable self</h3><p>If the class is <strong>not</strong> main-actor isolated, the same observer produces a different diagnostic:</p><pre>Capture of &#39;self&#39; with non-sendable type &#39;DataController&#39;<br>in a &#39;@Sendable&#39; closure</pre><p>The cause is different. A @Sendable closure can only capture Sendable values, and a plain class isn&#39;t Sendable. @MainActor classes are implicitly Sendable, which is why isolating the class removes this error and introduces the one in this article&#39;s title.</p><p>In Swift 5 mode, the usual workaround for this version is to hop onto the main actor explicitly:</p><pre>Task { @MainActor in<br>    self.objectWillChange.send()<br>}</pre><p>Note what this changes: the work is no longer synchronous. It runs on a later turn of the main actor, after the notification block returns.</p><h3>The tempting fix: nonisolated</h3><p>If the method’s isolation is the problem, removing it looks like the obvious answer. Local functions aren’t inferred to be @Sendable, so the method also has to move out of init:</p><pre>nonisolated func remoteStoreChanged(_ notification: Notification) {<br>    self.objectWillChange.send()<br>}</pre><p>A nonisolated method has a function type that matches the parameter, and the conversion error goes away. But the problem hasn&#39;t been solved, only moved:</p><ul><li>The method body still reads self.objectWillChange, a member of a main-actor-isolated instance.</li><li>A nonisolated method can be called from any thread, so the isolation the compiler just stopped enforcing is now your responsibility.</li></ul><p>If the compiler accepts the body, you’ve silenced a check, not satisfied it. The error was a symptom, and this approach removes the symptom while keeping the underlying issue.</p><p>It also has a lifetime problem. Passing remoteStoreChanged as a method reference captures self strongly. Block-based observers stay registered until removed, so the controller is retained indefinitely. This matters for anything that creates controller instances repeatedly, such as static let preview configurations or tests: every instance leaks.</p><h3>The solution: an inline closure that re-enters the main actor</h3><pre>@MainActor<br>class DataController: ObservableObject {<br>    let container: NSPersistentContainer<br><br>    init(inMemory: Bool = false) {<br>        // ... container setup ...<br><br>        NotificationCenter.default.addObserver(<br>            forName: .NSPersistentStoreRemoteChange,<br>            object: container.persistentStoreCoordinator,<br>            queue: .main<br>        ) { [weak self] _ in<br>            MainActor.assumeIsolated {<br>                self?.objectWillChange.send()<br>            }<br>        }<br>    }<br><br>    static let preview: DataController = {<br>        let dataController = DataController(inMemory: true)<br>        dataController.sampleData()<br>        return dataController<br>    }()<br>}</pre><p>Each part does specific work:</p><ul><li><strong>Inline closure.</strong> The closure literal is inferred as @Sendable because of the parameter it&#39;s passed to. No function-type conversion is involved, so nothing is lost.</li><li><strong>[weak self].</strong> The notification center no longer retains the controller. If the controller is deallocated, self? simply does nothing.</li><li><strong>MainActor.assumeIsolated.</strong> The body tells the compiler it is running on the main actor and executes the closure synchronously. Because queue: .main guarantees delivery on the main queue, that assumption is true.</li></ul><p>assumeIsolated is a runtime assertion, not a hop. If the closure were ever called from another thread, it would trap. Here the queue: .main argument and the assumeIsolated call must stay in agreement: change one and you must change the other. It requires Swift 5.9 or later.</p><h3>Choosing between the approaches</h3><pre><strong>Approach</strong>          <strong>Synchronous</strong>        <strong>Compiler</strong>              <strong>Notes</strong><br>                                     <strong>-verified</strong><br>------------------------------------------------------------------------------<br><em>nonisolated</em>       Yes                No                    Moves the isolation<br>method                                                     problem into the <br>                                                           method body ; <br>                                                           strong <em>self</em> capture<br>------------------------------------------------------------------------------<br>Closure + <em>Task</em>    No                 Yes                   Safe default when<br><em>{ @MainActor in }</em>                                          delivery order<br>                                                           isn&#39;t critical<br>------------------------------------------------------------------------------<br>Closure +         Yes                Runtime               Right choice when<br><em>MainActor</em>                            check                 <em>queue: .main</em> <br><em>.assumeIsolated</em>                                            already guarantees<br>                                                           the thread<br>------------------------------------------------------------------------------</pre><h3>Takeaways</h3><ul><li>A @Sendable parameter only accepts a function value that is itself @Sendable.</li><li>A @MainActor function can&#39;t be converted to a non-isolated function type without losing its isolation, and the compiler will refuse.</li><li>queue: .main is a runtime guarantee. The compiler can&#39;t see it, so you have to state it with MainActor.assumeIsolated or an explicit hop.</li><li>When a concurrency diagnostic appears, make the isolation correct rather than removing it. nonisolated is the right tool for members that don&#39;t touch isolated state, not for silencing errors.</li></ul><p><strong>Thank you for reading !</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a223775e25d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Concurrency — What Is an Actor, and When Should You Use One?]]></title>
            <link>https://medium.com/@swifttoday/swift-concurrency-what-is-an-actor-and-when-should-you-use-one-ad857c0c06f1?source=rss-8f60b87c00e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad857c0c06f1</guid>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[SwiftToday]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 07:01:01 GMT</pubDate>
            <atom:updated>2026-10-02T18:56:01.956Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift • iOS &amp; macOS • Concurrency</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-WGvErUyD-6PAW7qtg07BQ.png" /></figure><blockquote><strong>TL;DR:</strong> When shared mutable state needs to be accessed by multiple concurrent tasks, an actor ensures that only one task can access that state at a time — without locks, without manual synchronisation, and with the compiler enforcing the boundary.</blockquote><h3>What an actor is</h3><p>An actor is a nominal type, declared with the actor keyword:</p><pre>actor User { }</pre><p>Like a class, an actor is a <strong>reference type</strong>. It can have stored properties, computed properties, methods, initialisers, and subscripts. It can conform to protocols.</p><p>Unlike a class, an actor:</p><ul><li>Does not support inheritance</li><li>Cannot be marked final or use override</li><li>Cannot have convenience initialisers</li><li>Cannot delegate its own initialisation to another initialiser of the same actor</li></ul><p>These constraints exist because actors are not designed as a class replacement. They exist to solve a specific problem: <strong>protecting mutable state from concurrent access.</strong></p><h3>The problem actors solve</h3><p>Consider a bank account represented as a class:</p><pre>class BankAccount {<br>    var balance: Decimal = 1000<br><br>    func deposit(_ amount: Decimal) {<br>        balance += amount<br>    }<br><br>    func withdraw(_ amount: Decimal) {<br>        balance -= amount<br>    }<br><br>    func transfer(_ amount: Decimal, to other: BankAccount) {<br>        guard balance &gt;= amount else { return }<br>        balance -= amount<br>        other.deposit(amount)<br>    }<br>}</pre><p>If two concurrent tasks call transfer on the same account in rapid succession, both may pass the guard check before either has had a chance to decrement balance. The result is a transfer that should have been rejected going through — a classic <strong>data race</strong>.</p><p>One approach is to introduce a lock:</p><pre>final class BankAccount: @unchecked Sendable {<br>    private let lock = NSLock()<br>    var balance: Decimal = 1000<br><br>    func deposit(_ amount: Decimal) {<br>        lock.withLock { balance += amount }<br>    }<br><br>    func withdraw(_ amount: Decimal) {<br>        lock.withLock { balance -= amount }<br>    }<br><br>    func transfer(_ amount: Decimal, to other: BankAccount) {<br>        lock.withLock {<br>            guard balance &gt;= amount else { return }<br>            balance -= amount<br>        }<br>        other.deposit(amount)<br>    }<br>}</pre><p>This works, but it has problems. NSLock.withLock <strong>blocks the calling thread synchronously</strong>. In Swift Concurrency&#39;s cooperative thread pool, blocking a thread starves other tasks that are waiting to run on it. The more contention there is on the lock, the more threads are blocked, and the worse the situation gets. The lock also has to be applied manually to every method that touches shared state — a discipline that is easy to break as the class grows.</p><p>It’s worth being precise about Sendable here: marking a class Sendable is a <em>promise</em> to the compiler that the type is safe to share across concurrency boundaries. With @unchecked Sendable, that promise is made without any compiler verification — the developer is solely responsible for ensuring it holds. Sendable does not enforce thread safety. It declares it.</p><p>Actors enforce it.</p><h3>Actors as isolated state</h3><p>Rewriting BankAccount as an actor:</p><pre>actor BankAccount {<br>    var id: String<br>    var balance: Decimal<br><br>    init(id: String, balance: Decimal) {<br>        self.id = id<br>        self.balance = balance<br>    }<br><br>    func deposit(_ amount: Decimal) {<br>        balance += amount<br>    }<br><br>    func withdraw(_ amount: Decimal) {<br>        balance -= amount<br>    }<br><br>    func transfer(_ amount: Decimal, to other: BankAccount) async {<br>        guard balance &gt;= amount else { return }<br>        balance -= amount<br>        await other.deposit(amount)<br>    }<br>}</pre><p>The actor provides a compiler-enforced guarantee: <strong>only one task can execute inside the actor at a time.</strong> If a second transfer request arrives while the first is in progress, it waits. The guard check and the decrement are guaranteed to be atomic from the actor&#39;s perspective — there is no window in which a second task can observe the balance before it has been updated.</p><p>No locks. No @unchecked Sendable. No manual discipline. The compiler does the work.</p><h3>Why accessing actors requires await</h3><p>Any property or method access that crosses an actor’s isolation boundary requires await:</p><pre>let account = BankAccount(id: &quot;001&quot;, balance: 1000)<br>let currentBalance = await account.balance</pre><p>The await signals that the calling task may need to suspend until the actor is available. If the actor is currently executing another task, the caller suspends and yields the thread — keeping the cooperative thread pool healthy rather than blocking it.</p><p>This applies in three situations:</p><ol><li><strong>Access from outside the actor</strong> — any code not inside the actor’s own methods</li><li><strong>Access from one actor instance to a different actor instance</strong> — even if both are the same type</li><li><strong>Access between two different actor types</strong></li></ol><p>That second point is worth examining in detail:</p><pre>actor User {<br>    var score: Int = 10<br><br>    func copyScore(from other: User) async {<br>        score = await other.score<br>    }<br>}</pre><p>copyScore is inside the User actor, but other is a <em>different</em> User instance. Actor isolation is per-instance, not per-type. self and other are two separate isolation domains, and crossing between them requires await. The fact that both are User is irrelevant — what matters is that they are distinct actors.</p><h3>nonisolated — opting out of isolation</h3><p>Methods and properties inside an actor are isolated by default. nonisolated removes a specific member from the actor&#39;s isolation domain:</p><pre>actor BankAccount {<br>    var balance: Decimal = 1000<br>    let accountNumber: String = &quot;XXXX-XXXX-XXXX-XXXX-XXX-XX&quot;<br><br>    nonisolated func formattedAccountNumber() -&gt; String {<br>        return &quot;Account: \(accountNumber)&quot;<br>    }<br>}</pre><p>A nonisolated member can be called without await, from any context, without suspending. This is useful for:</p><ul><li>Protocol conformances that require synchronous methods (e.g. CustomStringConvertible)</li><li>Pure computations that don’t access actor state</li><li>Access to let constants, which are safe to read concurrently because they never change</li></ul><p>What nonisolated cannot do is access actor-isolated mutable state. Attempting it produces a compiler error:</p><pre>actor BankAccount {<br>    var balance: Decimal = 1000<br><br>    nonisolated func accountSummary() -&gt; String {<br>        return &quot;Balance: \(balance)&quot;<br>        // ❌ Actor-isolated property &#39;balance&#39; can not be referenced<br>        //    from a non-isolated context<br>    }<br>}</pre><p>Adding async/await inside the method does not resolve this — nonisolated removes the method from the isolation domain entirely, so the actor&#39;s executor is no longer in scope. The method either needs to become isolated (by removing nonisolated), or it needs to avoid touching actor state altogether.</p><h3>@MainActor — the actor you&#39;re already using</h3><p>The most widely encountered actor in SwiftUI development is one you may not have thought of as an actor: @MainActor.</p><p>@MainActor is a global actor that ensures all code annotated with it runs on the main thread. SwiftUI views and ObservableObject subclasses are implicitly @MainActor-isolated — which is why UI updates from background tasks require explicit dispatch back to the main thread, and why the compiler will warn you if you attempt to update UI state from a non-isolated async context.</p><pre>@MainActor<br>class ViewModel: ObservableObject {<br>    @Published var title: String = &quot;&quot;<br><br>    func loadData() async {<br>        let result = await fetchFromNetwork()<br>        title = result // Safe — we&#39;re on the main actor<br>    }<br>}</pre><p>Understanding actors generally makes @MainActor behaviour significantly easier to reason about. The rules are the same — isolation, await at the boundary, one task at a time — applied specifically to the main thread.</p><h3>When to use an actor</h3><p>Use an actor when:</p><ul><li>A reference type has <strong>mutable state</strong> that will be read or written by more than one concurrent task</li><li>You need the compiler to <strong>enforce</strong> the thread-safety boundary, not just document it</li><li>The shared state represents a real entity with identity — an account, a cache, a session, a connection</li></ul><p>Don’t reach for an actor when:</p><ul><li>The type is a value type — use a struct, which is copied rather than shared</li><li>The state is read-only — immutable data is safe to share without isolation</li><li>The type only ever runs on the main thread — @MainActor may be the more appropriate tool</li><li>There is no actual concurrency — adding an actor to synchronous code introduces unnecessary await overhead for no benefit</li></ul><h3>Summary</h3><pre>                     <strong>Class</strong>                         <strong>Actor<br>---------------------------------------------------------------------------<br>Reference type:       </strong>Yes<strong>                          </strong>Yes<strong><br>---------------------------------------------------------------------------<br>Inheritance:          </strong>Yes<strong>                          </strong>No<strong><br>---------------------------------------------------------------------------<br>Mutable shared:      </strong>Unsafe by<strong>                     </strong>Isolated<strong><br>state                </strong>default <strong>                      </strong>by default<strong><br>---------------------------------------------------------------------------<br>Cross Boundary:      </strong>Synchronous<strong>                   </strong>Requires `await`<strong><br>access<br>---------------------------------------------------------------------------<br>Thread safety:       </strong>Manual<em>(NSLock,</em><strong>                </strong>Compiler-enforced<strong><br>                     </strong><em>@unchecked Sendable)</em><strong><br>---------------------------------------------------------------------------<br>Main thread:         </strong>Manual<em>(DispatchQueue </em><strong>         </strong>@MainActor<strong><br>guarantee            </strong><em>.main)</em></pre><p>An actor is not a replacement for a class. It is a purpose-built tool for one specific problem: ensuring that mutable state shared across concurrent tasks is accessed safely, with the compiler doing the enforcement rather than the developer.</p><p><strong>Thank you for reading !</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad857c0c06f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ForEach ID Duplicated — What it Means and How to Fix it]]></title>
            <link>https://medium.com/@swifttoday/foreach-id-duplicated-what-is-means-and-how-to-fix-it-b7ee1fd8cb42?source=rss-8f60b87c00e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7ee1fd8cb42</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[SwiftToday]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 07:01:04 GMT</pubDate>
            <atom:updated>2026-09-23T11:48:27.961Z</atom:updated>
            <content:encoded><![CDATA[<h4>Swift • iOS &amp; macOS • SwiftUI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uarFtM19PR2g5IHAsNioDg.png" /></figure><blockquote><strong>TL;DR:</strong> ForEach ID duplicated is almost always a view-identity problem, not a rendering problem. SwiftUI relies on stable, unique IDs to track views across updates — derive and persist them from the actual underlying data entity, not from values that can collide or change.</blockquote><h3>The nature of the problem</h3><p>SwiftUI is a declarative framework. You describe the UI you want, and the framework figures out how to get there. That process — diffing the previous state against the new one and computing the minimum set of changes — requires SwiftUI to know which view corresponds to which piece of data across updates.</p><p>ForEach is the mechanism through which that mapping is established for collections. Every element you pass to ForEachneeds an identity: a value the framework can use to say <em>this view belongs to this datum, now and after the next state change.</em></p><p>The relationship looks like this:</p><pre>DATA<br> ↓<br>IDENTITY<br> ↓<br>VIEW</pre><p>When two elements share the same identity, SwiftUI cannot maintain that mapping reliably. The warning it surfaces reflects exactly that:</p><pre>ForEach&lt;Array&lt;...&gt;, ..., ...&gt;: the ID 123 occurs multiple times<br>within the collection, this will give undefined results.</pre><p>Undefined is the operative word. SwiftUI makes no guarantee about what it will render, animate, or preserve when identity is ambiguous.</p><h3>A minimal example</h3><pre>struct Item {<br>    let name: String<br>}<br><br>let items = [<br>    Item(name: &quot;Apple&quot;),<br>    Item(name: &quot;Banana&quot;),<br>    Item(name: &quot;Apple&quot;)<br>]<br><br>ForEach(items, id: \.name) { item in<br>    Text(item.name)<br>}</pre><p>The instruction here is: <em>use </em><em>name as the identity for each element.</em> Two elements share the name &quot;Apple&quot;. SwiftUI immediately sees a collision and emits the warning.</p><p>The type of the ID field doesn’t change the underlying issue. The problem is the guarantee — or lack of one — that the chosen key is unique across the collection.</p><h3>Common cases that catch developers off guard</h3><h4>Using \.self on a collection with duplicates</h4><pre>let names = [&quot;Apple&quot;, &quot;Banana&quot;, &quot;Apple&quot;]<br><br>ForEach(names, id: \.self) { name in<br>    Text(name)<br>}</pre><p>\.self uses the value itself as the identity. For value types, that means the hash of the value. Two identical strings hash identically — so &quot;Apple&quot; appears twice with the same ID, and the warning fires regardless.</p><h4>Integer IDs that aren’t actually unique</h4><pre>struct Item {<br>    let id: Int<br>    let name: String<br>}<br><br>let items = [<br>    Item(id: 1, name: &quot;Apple&quot;),<br>    Item(id: 2, name: &quot;Banana&quot;),<br>    Item(id: 1, name: &quot;Orange&quot;)<br>]<br><br>ForEach(items, id: \.id) { item in<br>    Text(item.name)<br>}</pre><p>The name fields are distinct, but SwiftUI uses id as the identity. Items with id: 1 are indistinguishable from SwiftUI&#39;s perspective, despite displaying different content.</p><p>Integer IDs are safe when they are structurally guaranteed to be unique — primary keys from an auto-incrementing database (MySQL, PostgreSQL, and similar) are the canonical example.</p><h4>Optional collections</h4><pre>let dates: [Date?] = [<br>    Date(),<br>    nil,<br>    Date(),<br>    nil<br>]<br><br>ForEach(dates, id: \.self) { date in<br>    // ...<br>}</pre><p>When using \.self on an optional type, SwiftUI hashes the wrapped value. Optional.none — nil — has no wrapped value to differentiate it from any other nil of the same type. Every nil element hashes identically, producing as many duplicate IDs as there are nil entries in the collection.</p><p>If you need to iterate over an optional collection, either filter out nils before the ForEach, or use an index-based approach with an explicit identity strategy.</p><h3>How to fix it</h3><h4>Conform to Identifiable with a stable UUID</h4><p>The most common and idiomatic solution is to conform your model type to Identifiable and assign each instance a UUID at creation time:</p><pre>struct Item: Identifiable {<br>    let id = UUID()<br>    let name: String<br>}</pre><p>Because id is a stored constant — not computed — each Item receives its UUID once, when the instance is initialised, and retains it for its lifetime.</p><p>This matters more than it might seem. Compare these two declarations:</p><pre>// 1 — UUID stored at init time<br>struct Item: Identifiable {<br>    let id = UUID()<br>    let name: String<br>}<br><br>// 2 — UUID provided externally<br>struct Item: Identifiable {<br>    let id: UUID<br>    let name: String<br>}</pre><p>The second form is correct when the UUID originates from a persistent source — a database record, a server response — and must round-trip through the system. It becomes a problem when it’s used like this:</p><pre>items.map { ViewModel(id: UUID(), ...) }</pre><p>Every time that transformation runs — on every state update — each element receives a brand-new UUID. SwiftUI sees an entirely new set of objects. The consequences include lost view state, unexpected insertion and deletion animations, unnecessary view recreation, and broken selection or focus behaviour.</p><p>The rule is straightforward: <strong>a stable ID must come from the entity itself, not from the code path that transforms or displays it.</strong></p><h3>Composite identity</h3><p>Sometimes no single field is guaranteed unique, but a combination of fields is. Rather than compromising on a weak identity, encode the composite key explicitly:</p><pre>struct CompositeID: Hashable {<br>    let playerID: Int<br>    let gameID: Int<br>}<br><br>struct Score {<br>    let compositeID: CompositeID<br>    let playerID: Int<br>    let gameID: Int<br>    var playerName: String<br><br>    init(playerID: Int, gameID: Int, playerName: String) {<br>        self.compositeID = CompositeID(playerID: playerID, gameID: gameID)<br>        self.playerID = playerID<br>        self.gameID = gameID<br>        self.playerName = playerName<br>    }<br>}<br><br>struct ScoreboardView: View {<br>    let scores: [Score] = [<br>        .init(playerID: 2, gameID: 2, playerName: &quot;Alice&quot;),<br>        .init(playerID: 1, gameID: 4, playerName: &quot;Bob&quot;)<br>    ]<br><br>    var body: some View {<br>        VStack {<br>            ForEach(scores, id: \.compositeID) { score in<br>                Text(score.playerName)<br>            }<br>        }<br>    }<br>}</pre><p>CompositeID conforms to Hashable, which Swift synthesises automatically when all stored properties are themselves Hashable. The combination of playerID and gameID uniquely identifies each score record, even when neither field alone would.</p><h3>Debugging duplicate IDs</h3><p>When the warning appears and the source isn’t immediately obvious, inspect the ID set before the ForEach:</p><pre>print(items.map(\.id))<br>// [1, 2, 3, 2, 5] — the duplicate is immediately visible</pre><p>For a more precise diagnostic that identifies which values are duplicated and how many times:</p><pre>let ids = items.map(\.id)<br><br>let duplicates = Dictionary(grouping: ids, by: { $0 })<br>    .filter { $1.count &gt; 1 }<br><br>print(&quot;Duplicate IDs:&quot;, duplicates)<br>// [&quot;2&quot;: [2, 2]] — key is the duplicate value, array shows occurrences</pre><p>This works for any Hashable ID type and scales well to larger collections where a visual scan of the array wouldn&#39;t be practical.</p><h3>What not to do</h3><p>When the warning appears, two patterns tend to surface as quick silencers:</p><pre>ForEach(items.indices, id: \.self) { index in<br>    Text(items[index].name)<br>}</pre><pre>ForEach(items, id: \.self)</pre><p>Both suppress the warning in certain cases, but neither addresses the underlying issue. Index-based identity is positional — if the collection reorders, SwiftUI associates the wrong view with the wrong datum. Using \.self on a non-unique collection defers the collision rather than preventing it.</p><p>Adding a fresh UUID() inside the view body is worse still:</p><pre>ForEach(items) { item in<br>    SomeView()<br>        .id(UUID()) // ❌ New UUID on every render<br>}</pre><p>Every render produces a new identity for every view. SwiftUI destroys and recreates the entire list on each update.</p><p>The goal is not to make SwiftUI stop emitting the warning. The goal is to give every logical element in the collection a unique, stable identity that persists across state changes.</p><h3>Decision guide</h3><p>When writing a ForEach, the question to answer first is whether the chosen identity is both <strong>unique</strong> and <strong>stable</strong>:</p><pre>What am I iterating over?<br>        ↓<br>Real entities (structs, models, records)?<br>        ↓ YES<br>Does each entity have a stable, unique ID?<br>        │<br>   ┌────┴────┐<br>  YES        NO<br>   ↓          ↓<br>ForEach    Assign one — UUID at init,<br>(items)    composite key, or DB primary key</pre><p>For simple types:</p><pre>String / Int / enum / Bool / etc.<br>              ↓<br>Are all values in the collection guaranteed unique?<br>              │<br>        ┌─────┴──────┐<br>       YES            NO<br>        ↓              ↓<br>    \.self        Wrap in a struct<br>                  with a stable ID</pre><p>Identity in SwiftUI is not a detail to resolve after the fact. It is a property of the data model — and the right place to establish it is there.</p><p><strong>Thank you for reading !</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7ee1fd8cb42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift typealias — What It Is, What It Does, and Why It Matters]]></title>
            <link>https://medium.com/@swifttoday/swift-typealias-what-it-is-what-it-does-and-why-it-matters-0b6e4456feb4?source=rss-8f60b87c00e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b6e4456feb4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[macos]]></category>
            <dc:creator><![CDATA[SwiftToday]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 07:01:03 GMT</pubDate>
            <atom:updated>2026-07-24T07:01:03.173Z</atom:updated>
            <content:encoded><![CDATA[<h4>Swift • iOS &amp; macOS • SwiftUI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHQCsmUWmC3tlQQx8JW4IA.png" /></figure><p>typealias is one of Swift&#39;s quieter features. It doesn&#39;t introduce new runtime behaviour, it doesn&#39;t change how your app performs, and it won&#39;t appear in any &quot;top 10 Swift tricks&quot; roundup. What it does — when used deliberately — is make code significantly easier to read, maintain, and reason about.</p><p>This article covers what typealias actually is, the five contexts where it earns its place, and the one common misuse that gives developers a false sense of type safety.</p><h3>What typealias does</h3><p>A typealias gives an existing type a new name. That&#39;s the entirety of what it does.</p><pre>typealias Identifier = String</pre><p>It does not define a new type. It does not wrap, extend, or modify the original. The compiler treats the alias and the original as identical — at compile time, the alias is erased entirely and replaced with whatever it points to.</p><p>This is a critical distinction, and one we’ll return to at the end.</p><h3>1. Resolving naming conflicts</h3><p>The most unambiguous argument for typealias is disambiguation — specifically, resolving conflicts between types that share a name across different frameworks.</p><p>Consider this common pairing:</p><pre>import StoreKit<br>import SwiftUI</pre><p>Both frameworks define a type called Transaction. Write a function that uses one without qualification:</p><pre>func subscriptionRestore(<br>    transaction: Transaction,<br>    token: String<br>) async -&gt; Bool {<br>    // ...<br>}</pre><p>The compiler immediately throws:</p><pre>&#39;Transaction&#39; is ambiguous for type lookup in this context<br>Found this candidate (StoreKit.Transaction)<br>Found this candidate (SwiftUI.Transaction)</pre><p>These are not the same type. StoreKit.Transaction represents a financial event — a purchase, a renewal, a refund. SwiftUI.Transaction is an animation context passed through the view hierarchy when state changes. Entirely different domains, identical names.</p><p>The compiler cannot infer intent. typealias resolves this by making the intent explicit:</p><pre>typealias StoreTransaction = StoreKit.Transaction<br>typealias AnimationTransaction = SwiftUI.Transaction<br><br>func subscriptionRestore(<br>    transaction: StoreTransaction,<br>    token: String<br>) async -&gt; Bool {<br>    // ...<br>}</pre><p>The ambiguity disappears. The compiler knows exactly which Transaction is meant, and any reader of the code does too — without having to check the import list.</p><h3>2. Making complex types readable</h3><p>Certain Swift types are inherently verbose. A nested generic that combines Result, a dictionary, and an array can become genuinely difficult to parse at a glance:</p><pre>let completion: (Result&lt;[String: [Int]], Error&gt;) -&gt; Void</pre><p>Written once, that’s manageable. Written across a codebase — in function signatures, stored properties, protocol requirements — it becomes noise. It also introduces risk: copy-pasting a complex type is an invitation for a subtle typo that the compiler may or may not catch immediately.</p><p>A typealias centralises the definition:</p><pre>typealias CompletionHandler = (Result&lt;[String: [Int]], Error&gt;) -&gt; Void<br><br>let completion: CompletionHandler</pre><p>If the underlying type ever needs to change, it changes in one place. Every usage updates automatically.</p><h3>3. Naming closures</h3><p>Closure types are among the most syntactically dense constructs in Swift. A function signature that takes an escaping closure inline offers the reader very little:</p><pre>func login(completion: @escaping (Bool, Error?) -&gt; Void)</pre><p>A typealias gives the closure a name that communicates its role:</p><pre>typealias LoginCompletion = (Bool, Error?) -&gt; Void<br><br>func login(completion: @escaping LoginCompletion)</pre><p>The signature now reads as intent rather than structure. A developer unfamiliar with this function understands immediately what LoginCompletion represents — without needing to mentally parse the tuple and return type.</p><p>This is particularly valuable in larger codebases where the same closure shape appears in multiple contexts. Define it once, name it clearly, reference it everywhere.</p><h3>4. Insulating against implementation changes</h3><p>As a project grows, types that seemed settled have a way of changing. A typealias can act as an abstraction layer between your codebase and the types it depends on.</p><p>Consider a network layer that standardises on a Response type:</p><pre>typealias Response = Result&lt;Data, NetworkError&gt;</pre><p>Every function in the network layer returns a Response. Now suppose the project&#39;s requirements evolve, and Data needs to be replaced with a custom ResponseData type. The change is contained:</p><pre>// Before<br>typealias Response = Result&lt;Data, NetworkError&gt;<br><br>// After<br>typealias Response = Result&lt;ResponseData, NetworkError&gt;</pre><p>Every caller picks up the new type automatically. No find-and-replace, no risk of missing an occurrence, no inconsistency introduced in the transition.</p><p>This same pattern works inside protocols, which is particularly useful when defining service interfaces:</p><pre>protocol APIService {<br>    typealias Response = Result&lt;ResponseData, NetworkError&gt;<br>}</pre><p>Any conforming type inherits the associated Response definition, keeping the contract consistent across implementations.</p><h3>5. Simplifying generics</h3><p>Generic types that appear repeatedly throughout a codebase benefit from a stable, readable name:</p><pre>// Without<br>var users: [UUID: User]<br><br>// With<br>typealias UserDictionary = [UUID: User]<br>var users: UserDictionary</pre><p>The payoff scales with complexity. A [UUID: User] dictionary is still readable. A [String: [UUID: [Event]]] structure is not — and a typealias that gives it a meaningful name makes every declaration, function signature, and protocol requirement that references it substantially clearer.</p><h3>One thing to avoid</h3><p>typealias creates an alias, not a type. The practical consequences of that distinction are easy to underestimate.</p><pre>typealias Age = Int<br>typealias Price = Int</pre><p>To the compiler, these three are identical:</p><pre>Age == Int == Price</pre><p>The alias is erased at compile time. The type checker never sees Age or Price — it sees Int. Which means the following compiles without a single warning:</p><pre>func applyDiscount(to price: Price, years: Age) -&gt; Price {<br>    return price - years // Logically wrong. Perfectly valid Swift.<br>}</pre><p>An age has been subtracted from a price. The compiler cannot catch it, because there is nothing to catch — both values are Int.</p><p>If the distinction between Age and Price needs to be enforced by the type system, a struct is the correct tool:</p><pre>struct Age {<br>  let value: Int<br>}<br><br>struct Price {<br>  let value: Int<br>}</pre><p>Age and Price are now distinct nominal types. Swift uses nominal typing — two types are compatible only if they share an explicit relationship through inheritance, conformance, or identity. These two structs share none. They both wrap an Int, but they are not Int, and they are not each other.</p><pre>let age = Age(value: 30)<br>let price = Price(value: 100)<br><br>let wrong: Price = age<br>// ❌ Cannot convert value of type &#39;Age&#39; to specified type &#39;Price&#39;</pre><p>The compiler now enforces the boundary at build time.</p><p>This pattern — wrapping a primitive in a single-value struct to create a semantically distinct type — is known as a <strong>newtype</strong>. It’s a first-class language feature in Haskell and Rust; in Swift, the single-value struct is the idiomatic equivalent.</p><p>Once your structs are in place, typealias can still play a role — now layered on top of the type-safe foundation:</p><pre>typealias PeopleAge = Age<br>typealias ArticlePrice = Price</pre><p>PeopleAge aliases Age, not Int. The struct&#39;s type safety is fully preserved. PeopleAge and ArticlePrice remain incompatible with each other and with raw Int values. The alias now serves its proper purpose: communicating context and intent at the call site, without weakening the type boundary.</p><p>One nuance worth noting: if you create multiple aliases of the same struct, those aliases remain interchangeable with each other, because they all resolve to the same underlying type. If you need the compiler to distinguish between them, they need separate structs.</p><h4>Summary</h4><pre>Use case                           What it solves<br>---------------------------------------------------------------------------<br>Naming conflicts                   Disambiguates types with<br>                                   identical names across frameworks<br>---------------------------------------------------------------------------<br>Complex types                      Centralises verbose type<br>                                   declarations in one place<br>---------------------------------------------------------------------------<br>Closure naming                     Gives closure types a readable,<br>                                   role-describing name<br>---------------------------------------------------------------------------<br>Implementation                     Absorbs type changes without<br>insulation                         propagating edits across the codebase<br>---------------------------------------------------------------------------<br>Generic                            Reduces noise from repeated,<br>simplification                     verbose generic declarations<br>---------------------------------------------------------------------------</pre><p>The underlying principle is simple:</p><blockquote>typealias is a clarity tool, not a type creation mechanism. If an alias doesn&#39;t make the code more immediately readable, the original type is probably the better choice.</blockquote><p>Used with that in mind, typealias is one of the more reliable tools Swift gives you for keeping a growing codebase legible.</p><p><strong>Thank you for reading !</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b6e4456feb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vapor & Idempotency: Why HTTP Method Semantics Matter More Than You Think]]></title>
            <link>https://medium.com/@swifttoday/vapor-idempotency-why-http-method-semantics-matter-more-than-you-think-ff77174e5888?source=rss-8f60b87c00e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff77174e5888</guid>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[vapor]]></category>
            <dc:creator><![CDATA[SwiftToday]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 07:01:02 GMT</pubDate>
            <atom:updated>2026-07-10T07:01:02.158Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Swift · Server-Side · Vapor</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AgXDE2akadbaj5iWAv9lnQ.png" /></figure><p>While developing a Vapor server, I rediscovered something that doesn’t get talked about nearly enough in back-end tutorials: idempotency. It’s one of those concepts that’s easy to skip past early on and quietly expensive to ignore in production.</p><h3>What idempotency means</h3><p>An HTTP method is <strong>idempotent</strong> if sending the same request multiple times produces the same effect on the server as sending it once.</p><p>That definition is precise, but the motivation is practical: <strong>modern networks are unreliable.</strong> A client may not receive a response because:</p><ul><li>The connection timed out before the response arrived</li><li>The server restarted after processing the request but before replying</li><li>A proxy dropped the response in transit</li><li>A mobile device switched networks mid-request</li></ul><p>In all of these cases, the client doesn’t know whether the request succeeded. It only knows it didn’t get a response. The natural reaction is to retry — and if your endpoint isn’t idempotent, that retry can cause real damage.</p><h3>POST: neither safe nor idempotent</h3><p>POST is the clearest example of a non-idempotent method because it&#39;s designed to create a new resource on every call.</p><p>Here’s a Vapor route that creates a user. Note that in production Vapor, you’d typically use a separate DTO struct for the request body rather than decoding directly into your model — this keeps your API contract separate from your database schema and prevents clients from setting fields they shouldn’t control:</p><pre>// Models/CreateUser.swift<br>final class CreateUser: Model, Content, @unchecked Sendable, Authenticatable {<br>    static let schema: String = &quot;users&quot;<br><br>    @ID(key: .id)<br>    var id: UUID?<br><br>    @Field(key: &quot;name&quot;)<br>    var name: String<br><br>    @Field(key: &quot;email&quot;)<br>    var email: String<br><br>    init() { }<br><br>    init(id: UUID? = nil, name: String, email: String) {<br>        self.id = id<br>        self.name = name<br>        self.email = email<br>    }<br>}<br><br>// A separate struct for decoding the request body<br>struct CreateUserRequest: Content {<br>    var name: String<br>    var email: String<br>}</pre><pre>// Routes/UserRoutes.swift<br>app.post(&quot;users&quot;) { req async throws -&gt; CreateUser in<br>    let input = try req.content.decode(CreateUserRequest.self)<br>    let user = CreateUser(<br>        name: input.name,<br>        email: input.email<br>    )<br>    try await user.save(on: req.db)<br>    return user<br>}</pre><p>With this request body:</p><pre>{<br>  &quot;name&quot;: &quot;Jane Doe&quot;,<br>  &quot;email&quot;: &quot;janedoe@example.com&quot;<br>}</pre><p>The first call creates the user. If the response never reaches the client and they retry, a second user record is created with the same data. Now there are two accounts for Jane Doe.</p><p>A well-configured database can partially mitigate this by adding a unique constraint on the email column — and it should. But that&#39;s a database-level safeguard against duplicates, not a solution to the broader reliability problem. What if the operation isn&#39;t a user creation? What if it&#39;s a payment, a booking, or an order?</p><h3>The real fix: idempotency keys</h3><p>Authentication (JWT, bearer tokens) is important, but it’s a separate concern from idempotency. Authentication answers <em>who is making this request</em>. An idempotency key answers <em>has this exact request already been processed</em>?</p><p>An <strong>idempotency key</strong> is a client-generated UUID the client sends in a custom request header — conventionally Idempotency-Key. The server stores the key alongside the result of the first successful processing. If the same key arrives again, the server returns the stored result instead of executing the operation again.</p><p>Here’s how this looks in Vapor:</p><pre>// A simple in-memory idempotency store (use Redis or your DB in production)<br>actor IdempotencyStore {<br>    private var processed: [String: Response] = [:]<br><br>    func result(for key: String) -&gt; Response? {<br>        processed[key]<br>    }<br><br>    func store(key: String, response: Response) {<br>        processed[key] = response<br>    }<br>}<br><br>let idempotencyStore = IdempotencyStore()</pre><pre>app.post(&quot;users&quot;) { req async throws -&gt; Response in<br>    // 1. Extract the idempotency key from the request header<br>    guard let idempotencyKey = req.headers.first(name: &quot;Idempotency-Key&quot;) else {<br>        throw Abort(.badRequest, reason: &quot;Missing Idempotency-Key header&quot;)<br>    }<br><br>    // 2. If we&#39;ve seen this key before, return the stored result<br>    if let stored = await idempotencyStore.result(for: idempotencyKey) {<br>        return stored<br>    }<br><br>    // 3. Otherwise, process the request<br>    let input = try req.content.decode(CreateUserRequest.self)<br>    let user = CreateUser(name: input.name, email: input.email)<br>    try await user.save(on: req.db)<br><br>    // 4. Encode the response and store it against the key<br>    let response = try Response(<br>        status: .created,<br>        body: .init(data: JSONEncoder().encode(user))<br>    )<br>    await idempotencyStore.store(key: idempotencyKey, response: response)<br>    return response<br>}</pre><p>Now the flow for a network failure looks like this:</p><ol><li>Client sends POST /users with Idempotency-Key: abc-123 — user is created, response stored</li><li>Response is lost in transit — client receives nothing</li><li>Client retries with the same Idempotency-Key: abc-123</li><li>Server finds the stored result for abc-123 and returns it immediately — no second user created</li></ol><p>This is the pattern used by payment APIs like Stripe and PayPal for exactly this reason: when money is involved, a retry must never mean a double charge.</p><p>In production, the idempotency store should be backed by Redis or your database with a TTL on stored keys (24 hours is a common choice), rather than in-memory storage which doesn’t survive server restarts.</p><h3>The other HTTP methods</h3><p>Not all methods have the same idempotency story. It helps to think about two properties separately:</p><ul><li><strong>Safe</strong>: the request does not modify server state</li><li><strong>Idempotent</strong>: repeating the request has no additional effect on server state beyond the first call</li></ul><h3>GET — safe and idempotent</h3><pre>GET /users/42</pre><p>Retrieves data, doesn’t modify anything. Retrying returns the same data and changes nothing. Both safe and idempotent.</p><h3>DELETE — idempotent, not safe</h3><pre>DELETE /users/42</pre><ul><li>First call: user is deleted → 204 No Content</li><li>Second call: user is already gone → 404 Not Found</li></ul><p>The response differs between the two calls, but the server state does not — the user is deleted either way. This is the key distinction: <strong>idempotency is about the effect on the server, not about getting identical responses.</strong> DELETE is idempotent but not safe, because the first call does modify server state.</p><h3>PUT — idempotent, not safe</h3><pre>// PUT /users/42<br>{<br>  &quot;name&quot;: &quot;Alice&quot;,<br>  &quot;email&quot;: &quot;alice@example.com&quot;<br>}</pre><p>The first call sets the user’s name to Alice and email to alice@example.com. Repeating the same request produces the same result — the fields are already those values. PUT is idempotent because it replaces the entire resource to a specific state, so repeated calls converge on the same outcome.</p><h3>POST — neither safe nor idempotent</h3><p>As shown above: each call creates a new resource. Not safe (modifies server state), not idempotent (repeated calls produce additional effects).</p><h3>PATCH — depends on the implementation</h3><p>This is the one people most often get wrong. Whether PATCH is idempotent depends entirely on what the patch operation does:</p><pre>// ✅ Idempotent — sets a field to a specific value<br>// PATCH /users/42<br>{ &quot;name&quot;: &quot;Alice&quot; }<br><br>// ❌ Not idempotent — increments a counter; each call changes the result<br>// PATCH /counter/42<br>{ &quot;operation&quot;: &quot;increment&quot; }</pre><p>If PATCH sets a field to a specific value, it&#39;s idempotent. If it performs a relative change (increment, append, toggle), it is not. This matters when designing your API: if your PATCH endpoint performs relative operations, callers cannot safely retry it without idempotency keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HwNd09fpVH-Xd13QAUri7A.png" /></figure><p>Idempotency is foundational to reliable back-end design because it determines whether clients, load balancers, and API gateways can safely retry requests after network failures. Getting it wrong with POST means duplicate data at best, duplicate charges or orders at worst. Designing idempotent endpoints — or adding idempotency keys to those that aren&#39;t inherently idempotent — is one of the most practical reliability improvements you can make to a Vapor server.</p><p><strong>Thank you for reading !</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff77174e5888" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“The Compiler Is Unable to Type-Check This Expression in Reasonable Time” — What’s Actually Going…]]></title>
            <link>https://medium.com/@swifttoday/the-compiler-is-unable-to-type-check-this-expression-in-reasonable-time-whats-actually-going-c4768a8c299e?source=rss-8f60b87c00e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4768a8c299e</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[SwiftToday]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 15:05:10 GMT</pubDate>
            <atom:updated>2026-06-26T15:05:10.639Z</atom:updated>
            <content:encoded><![CDATA[<h3>“The Compiler Is Unable to Type-Check This Expression in Reasonable Time” — What’s Actually Going On</h3><p><strong>Swift · iOS &amp; macOS · Error Handling</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uarFtM19PR2g5IHAsNioDg.png" /></figure><p>Everyone runs into this one eventually, beginner or senior:</p><pre>The compiler is unable to type-check this expression in reasonable time;<br>try breaking up the expression into distinct sub-expressions.</pre><p>It almost always shows up on the var body: some View line, with no further explanation of what&#39;s actually too complex. This article explains why it happens, why it&#39;s not the old &quot;10-child ViewBuilder limit&quot; you may have read about elsewhere, and what to actually do about it.</p><h3>First, a necessary disclaimer: this is not the 10-child limit</h3><p>If you’ve been writing SwiftUI for a while, you may remember this error from code like:</p><pre>struct ContentView: View {<br>    var body: some View {<br>        VStack {<br>            Text(&quot;1&quot;)<br>            Text(&quot;2&quot;)<br>            Text(&quot;3&quot;)<br>            Text(&quot;4&quot;)<br>            Text(&quot;5&quot;)<br>            Text(&quot;6&quot;)<br>            Text(&quot;7&quot;)<br>            Text(&quot;8&quot;)<br>            Text(&quot;9&quot;)<br>            Text(&quot;10&quot;)<br>            Text(&quot;11&quot;) // ❌ Extra argument in call<br>        }<br>    }<br>}</pre><p>This used to fail because @ViewBuilder was implemented as a fixed set of overloads — buildBlock defined for one child, two children, three, and so on, up to ten:</p><pre>buildBlock&lt;C0&gt;(_ c0: C0)<br>buildBlock&lt;C0, C1&gt;(_ c0: C0, _ c1: C1)<br>// ... up to<br>buildBlock&lt;C0, C1, C2, C3, C4, C5, C6, C7, C8, C9&gt;(...)</pre><p>Swift didn’t yet have variadic generics, so the language had to write one overload per arity, and ten was where the line was drawn. Depending on your Swift and Xcode version, hitting this limit produced either:</p><pre>Extra argument in call</pre><p>or:</p><pre>Closure containing control flow statement cannot be used with result builders</pre><p><strong>That limit no longer exists</strong> for most SwiftUI containers, thanks to several Swift Evolution proposals delivered over a few years:</p><ul><li><strong>SE-0289 (Result Builders)</strong> — introduced @resultBuilder and the original buildBlock model that became the foundation @ViewBuilder is built on.</li><li><strong>SE-0348 (</strong><strong>buildPartialBlock for result builders)</strong> — let builders combine children one at a time via buildPartialBlock(first:) and buildPartialBlock(accumulated:next:), instead of requiring a hand-written overload for every possible number of children.</li><li><strong>SE-0393 (Value and Type Parameter Packs)</strong> — introduced repeat each and parameter packs, removing the need for fixed-arity generic overloads in functions.</li><li><strong>SE-0398 (Allow Generic Types to Abstract Over Packs)</strong> — extended the parameter pack model from functions to generic types themselves, letting a type like TupleView abstract over an arbitrary number of contained views:</li></ul><pre>// Conceptually, before parameter packs:<br>// a fixed overload like buildBlock&lt;C0, C1&gt;(_ c0: C0, _ c1: C1)<br><br>// After SE-0398, generic types can abstract over a pack directly:<br>struct TupleView&lt;repeat each Content&gt; { /* ... */ }</pre><p>So if you hit this error today, it has nothing to do with a child-count limit. The actual cause is something else entirely.</p><h3>What’s actually causing the error</h3><p>The error means Swift’s type checker is trying to resolve an expression with too many simultaneous possibilities to solve efficiently. It’s a <strong>type inference performance problem</strong>, not a hard structural limit. The compiler gives up after a certain amount of work rather than taking an unbounded amount of time.</p><p>This typically happens when several of the following are combined in a single view or expression:</p><ul><li>Nested generics</li><li>Long chained modifiers</li><li>Conditionals embedded inside the view hierarchy</li><li>Bindings combined with conditionals</li><li>Closures with inferred types</li><li>ForEach over computed or transformed data</li><li>NavigationStack combined with complex path logic</li><li>.sheet() or .toolbar() with inline, non-trivial content</li><li>Custom @ViewBuilder functions that are themselves complex</li></ul><p>Individually, none of these is a problem. The type checker struggles when several compound together in one expression, because resolving generic types and some View conformance becomes combinatorial rather than linear.</p><h3>Fixing it: four common patterns</h3><h4>1. Break up huge view hierarchies into components</h4><pre>// Before — everything inline<br>struct ContentView: View {<br>    var body: some View {<br>        HStack {<br>            ForEach(items) { item in<br>                Text(item.name)<br>                    .font(.headline)<br>                    .foregroundStyle(Color.primary)<br>                    .padding()<br>                    .background(Material.thin)<br>                    .cornerRadius(16)<br>            }<br>        }<br>    }<br>}</pre><pre>// After — extracted into its own view<br>struct ItemRow: View {<br>    var item: Item<br><br>    var body: some View {<br>        Text(item.name)<br>            .font(.headline)<br>            .foregroundStyle(Color.primary)<br>            .padding()<br>            .background(Material.thin)<br>            .cornerRadius(16)<br>    }<br>}<br><br>struct ContentView: View {<br>    var body: some View {<br>        HStack {<br>            ForEach(items) { item in<br>                ItemRow(item: item)<br>            }<br>        }<br>    }<br>}</pre><p>Extracting ItemRow gives the type checker a much smaller expression to resolve at each level, instead of one deeply nested generic chain.</p><h4>2. Simplify complex conditional logic</h4><p>Nested ternaries inside a view are a common trigger:</p><pre>// Before — nested ternaries make inference expensive<br>Text(<br>    isAdmin<br>        ? (isPremium ? &quot;Premium Admin&quot; : &quot;Admin&quot;)<br>        : (isPremium ? &quot;Premium User&quot; : &quot;User&quot;)<br>)</pre><pre>// After — resolve the string first, outside the view expression<br>let label: String = {<br>    switch (isAdmin, isPremium) {<br>    case (true, true): return &quot;Premium Admin&quot;<br>    case (true, false): return &quot;Admin&quot;<br>    case (false, true): return &quot;Premium User&quot;<br>    case (false, false): return &quot;User&quot;<br>    }<br>}()<br><br>Text(label)</pre><p>The key change is computing the plain String value separately, before it ever enters a view expression. The type checker then only has to resolve Text(String) — a trivial case — instead of inferring through nested ternaries inside a View-returning context.</p><h4>3. Break up long modifier chains</h4><pre>// Before — one long chain on an inline expression<br>struct ContentView: View {<br>    var body: some View {<br>        Text(&quot;Hello, World!&quot;)<br>            .font(.headline)<br>            .foregroundStyle(Color.primary)<br>            .padding()<br>            .background(Material.thin)<br>            .cornerRadius(16)<br>    }<br>}</pre><pre>// After — split the chain across a stored property and the body<br>struct ContentView: View {<br>    private let label = Text(&quot;Hello, World!&quot;)<br>        .font(.headline)<br>        .foregroundStyle(Color.blue)<br><br>    var body: some View {<br>        label<br>            .padding()<br>            .frame(width: 100, height: 80)<br>            .background(Material.thin)<br>            .clipShape(.capsule)<br>    }<br>}</pre><p>Splitting the chain gives the compiler two smaller expressions to type-check instead of one long one, and each is resolved independently.</p><h4>4. Extract large conditional closures into their own views</h4><pre>// Before — conditional branches duplicated inline inside ForEach<br>struct ContentView: View {<br>    var body: some View {<br>        HStack {<br>            ForEach(users) { user in<br>                if isFriend {<br>                    Text(user.name)<br>                        .font(.headline)<br>                        .foregroundStyle(Color.primary)<br>                        .padding()<br>                        .background(Material.thin)<br>                        .cornerRadius(16)<br>                } else {<br>                    Text(user.nickname)<br>                        .font(.headline)<br>                        .foregroundStyle(Color.primary)<br>                        .padding()<br>                        .background(Material.thin)<br>                        .cornerRadius(16)<br>                }<br>            }<br>        }<br>    }<br>}</pre><pre>// After — one small, reusable component<br>struct FriendRow: View {<br>    var displayName: String<br><br>    var body: some View {<br>        Text(displayName)<br>            .font(.headline)<br>            .foregroundStyle(Color.primary)<br>            .padding()<br>            .background(Material.thin)<br>            .cornerRadius(16)<br>    }<br>}<br><br>struct ContentView: View {<br>    var body: some View {<br>        HStack {<br>            ForEach(users) { user in<br>                FriendRow(displayName: isFriend ? user.name : user.nickname)<br>            }<br>        }<br>    }<br>}</pre><p>This collapses two duplicated branches into a single component call, and moves the conditional logic to a plain Stringdecision rather than a conditional view decision.</p><h3>How to find the problem when the error doesn’t point at it</h3><p>The compiler’s error location is often unhelpful — it usually points at var body as a whole rather than the specific sub-expression that&#39;s expensive. A reliable way to narrow it down:</p><ol><li>Comment out roughly half of the view’s content — whichever half looks the most complex.</li><li>Rebuild.</li><li>If the error disappears, the problem is in the commented-out half. If it persists, it’s in the half you kept.</li><li>Repeat, narrowing the range each time, until you isolate the specific expression.</li><li>Once found, extract it into its own View struct, or a @ViewBuilder function if it doesn&#39;t need to own state or identity — extracting into a separate type breaks the expression into something the compiler can resolve independently.</li></ol><h3>The takeaway</h3><p>This error is not a hard limit you’ve bumped into — it’s the compiler telling you an expression has become too combinatorially complex to resolve quickly. The fix is consistently the same shape: break the expression into smaller, independently-typed pieces, usually by extracting a subview or pre-computing a value outside the view hierarchy. Once the type checker isn’t trying to solve everything at once, the error disappears — and your view hierarchy usually ends up cleaner for it anyway.</p><p><strong>Thank you for reading !</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4768a8c299e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Update NavigationAuthority bound path tried to update multiple times per frame” — What It Means…]]></title>
            <link>https://medium.com/@swifttoday/update-navigationauthority-bound-path-tried-to-update-multiple-times-per-frame-what-it-means-13b48001e3bc?source=rss-8f60b87c00e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/13b48001e3bc</guid>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[SwiftToday]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 07:01:03 GMT</pubDate>
            <atom:updated>2026-06-19T07:01:03.211Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Update NavigationAuthority bound path tried to update multiple times per frame” — What It Means and How to Fix It</h3><p><strong>Swift · iOS &amp; macOS · SwiftUI</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vajqaNyuThM0EhUvJzqPAw.png" /></figure><blockquote>If you’ve already seen this message flood your Xcode console — sometimes appearing dozens of times in rapid succession — and your app runs perfectly fine on iOS but shows the warning on macOS, this article is for you.</blockquote><p>First, the reassurance: this is a <strong>SwiftUI runtime warning</strong>, not a bug specific to macOS. It surfaces more visibly on macOS because macOS renders navigation transitions differently, making timing violations more apparent. The underlying cause is the same on both platforms.</p><h3>What the warning means</h3><p>SwiftUI’s navigation system detected that your navigation state was modified <strong>more than once within a single render cycle</strong>. The framework expects navigation state to change at most once per frame — one push, one pop, one replacement. When it detects multiple modifications in the same cycle, it issues this warning because the behaviour is undefined: SwiftUI doesn’t guarantee which update wins, and the result can be an inconsistent navigation stack.</p><p>In practical terms: something in your code is calling path.append(), path.removeLast(), or modifying a navigation binding multiple times before SwiftUI has finished processing the first change.</p><h3>Common causes</h3><p><strong>1. Mutating navigation state directly inside </strong><strong>var body</strong></p><p>This is the most serious cause, and it goes beyond the navigation warning. The body property in SwiftUI is a pure computed property — it describes your UI, it does not perform side effects. Mutating state inside body is prohibited:</p><pre>// ❌ Never do this — mutating state during rendering is undefined behaviour<br>var body: some View {<br>    if condition {<br>        path.append(&quot;A&quot;)<br>    }<br>    return ContentView()<br>}</pre><p>SwiftUI evaluates body to produce a description of the interface, then applies changes through its diffing engine. Calling path.append() during that evaluation mutates state while a render is in progress, which immediately triggers another evaluation, which may mutate state again — a recursive loop that the runtime warning is trying to tell you about.</p><p><strong>2. Navigation triggered inside </strong><strong>.onAppear() without deferral</strong></p><p>.onAppear() fires during the view&#39;s first render cycle. Pushing to a navigation path from .onAppear() means you&#39;re modifying navigation state while the current view is still being installed:</p><pre>// ❌ Modifying navigation during the render that triggered onAppear<br>.onAppear {<br>    path.append(&quot;A&quot;)<br>}</pre><p><strong>3. Multiple </strong><strong>path mutations in one synchronous block</strong></p><p>Calling append or removeLast more than once without batching them triggers multiple navigation updates:</p><pre>// ❌ Two separate updates in the same synchronous call<br>path.append(&quot;A&quot;)<br>path.append(&quot;B&quot;)</pre><p><strong>4. Reactive loops: navigation state that updates itself</strong></p><p>If your navigation path is derived from a @State or @Published property that is <em>also updated by</em> navigation changes, you can create a cycle: state changes navigation, navigation changes state, state changes navigation again.</p><p><strong>5. Multiple async updates firing simultaneously</strong></p><p>Multiple Task {} closures or other async operations all updating path without coordination can collide within the same render frame.</p><h3>The Fixes</h3><h4>Fix 1: Move navigation mutations into .onChange(of:)</h4><p>The correct place to trigger navigation in response to a condition is .onChange(of:), not body. This modifier fires <em>after</em> the current render cycle completes, in a controlled context where navigation mutations are safe:</p><pre>// ✅ Navigation triggered after the render cycle, not during it<br>var body: some View {<br>    VStack {<br>        // Your UI<br>    }<br>    .onChange(of: condition) { newValue in<br>        if newValue {<br>            path.append(&quot;A&quot;)<br>        }<br>    }<br>}</pre><h4>Fix 2: Batch multiple path mutations</h4><p>If you need to push multiple views at once, use append(contentsOf:) to apply them as a single update rather than separate ones:</p><pre>// ✅ Single update, two destinations<br>path.append(contentsOf: [&quot;A&quot;, &quot;B&quot;])</pre><h4>Fix 3: Defer navigation to the next run loop</h4><p>For cases where navigation is triggered from .onAppear() or another lifecycle hook that fires mid-render, deferring the mutation to the next run loop gives SwiftUI time to finish the current cycle first.</p><p>Using Swift Concurrency (preferred):</p><pre>// ✅ Deferred to next run loop via Swift Concurrency<br>Task { @MainActor in<br>    path.append(&quot;A&quot;)<br>}</pre><p>Using DispatchQueue (acceptable for legacy code, but not recommended for new code):</p><pre>// ⚠️ Works, but operates outside Swift&#39;s concurrency model<br>DispatchQueue.main.async {<br>    path.append(&quot;A&quot;)<br>}</pre><p>Note: deferral is a <strong>timing fix</strong>, not a structural fix. If the warning is caused by a reactive loop — where navigation state and other state are driving each other — deferral will reduce the frequency of the warning but not eliminate the loop. In that case, the fix is architectural.</p><h4>Fix 4: Break reactive loops structurally</h4><p>If your navigation state is derived from and also updates the same source of truth, separate them. Navigation state should be a single source of truth that is written to intentionally, not derived reactively from something that is itself affected by navigation:</p><pre>// ❌ Binding loop: selectedItem drives navigation path,<br>// which updates selectedItem, which drives path again<br>@Published var selectedItem: Item?<br>var path: [Item] { selectedItem.map { [$0] } ?? [] }<br><br>// ✅ Navigation path is its own source of truth,<br>// updated intentionally in response to user actions<br>@Published var path: [Item] = []<br><br>func select(_ item: Item) {<br>    path = [item]<br>}</pre><h3>Why this is more visible on macOS</h3><p>macOS renders navigation transitions synchronously in contexts where iOS might defer them. This means the same timing violation that iOS renders without complaint (because the deferred render cycle absorbs it) gets flagged immediately on macOS because the render happens before the next opportunity for cleanup. The underlying violation is identical — macOS is simply less forgiving about it, which is actually useful: it surfaces problems earlier.</p><h3>What SwiftUI expects</h3><p>SwiftUI’s navigation system is built on two guarantees:</p><ul><li>Navigation state changes <strong>once per render cycle</strong>, producing a predictable transition</li><li>The view hierarchy is derived from state, never the other way around — state is never derived from or mutated by the rendering process itself</li></ul><p>When your code violates either of these, the NavigationAuthority warning is SwiftUI telling you that it cannot guarantee consistent behaviour. The warning is not cosmetic — an inconsistent navigation stack can produce flickering transitions, infinite re-render loops, and views that appear in the wrong order or fail to appear at all.</p><p>The fix is always some form of the same principle: let the current render cycle complete, then update navigation state once, intentionally.</p><p><strong>Thank you for reading !</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13b48001e3bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Concurrency vs Grand Central Dispatch: Why the Warning You’re Ignoring Actually Matters]]></title>
            <link>https://medium.com/@swifttoday/swift-concurrency-vs-grand-central-dispatch-why-the-warning-youre-ignoring-actually-matters-ab0b54f70fd0?source=rss-8f60b87c00e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab0b54f70fd0</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <dc:creator><![CDATA[SwiftToday]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 07:01:03 GMT</pubDate>
            <atom:updated>2026-06-12T13:08:39.571Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Swift · iOS &amp; macOS · Concurrency</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mtwiJk7qUpx-DYvy1kDozA.png" /></figure><p>Have you ever encountered a warning like this one and dismissed it because the code compiled fine?</p><pre>Capture of &#39;people&#39; with non-sendable type &#39;People&#39; in a @Sendable closure.<br>This is an error in the Swift 6 language mode.</pre><p>This article explains what that warning is actually telling you, why suppressing it with DispatchQueue is not the same as fixing it, and what the correct solution looks like.</p><h3>Where the warning comes from</h3><p>Consider a function that manages local notification reminders for a People object — a Core Data entity:</p><pre>func updateNotificationsReminder(for people: People) {<br>    removeNotificationsReminder(for: people)<br><br>    Task { @MainActor in<br>        if people.isPresent == true {<br>            let success = await addNotificationsReminder(for: people)<br><br>            if !success {<br>                print(&quot;Update failure for notification: \(people.peopleId)&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>When that function is called from another Task:</p><pre>Task { @MainActor [weak self] in<br>    guard let self else { return }<br>    self.updateNotificationsReminder(for: people)<br>    // ⚠️ Capture of &#39;people&#39; with non-sendable type &#39;People&#39; in a @Sendable closure.<br>}</pre><p>Xcode flags the people argument. The code compiles — in Swift 5 compatibility mode this is a warning. In Swift 6 strict concurrency mode it becomes a hard error. That distinction is why it&#39;s easy to ignore today and dangerous to leave unfixed.</p><h3>Why switching to DispatchQueue makes the warning disappear</h3><p>The immediate temptation is to reach for the older API:</p><pre>DispatchQueue.main.async {<br>    self.updateNotificationsReminder(for: people)<br>}</pre><p>The warning vanishes. But this is not a fix — it’s a blind spot.</p><p>DispatchQueue is a C-based concurrency API (<em>libdispatch</em>) that predates Swift&#39;s concurrency model entirely. Because it operates outside that model, the Swift compiler&#39;s Sendability and actor-isolation checks simply don&#39;t apply to it. The compiler isn&#39;t verifying that people is safe to cross a concurrency boundary — it&#39;s not checking at all.</p><p>The absence of a warning from DispatchQueue is not a safety guarantee. It&#39;s silence.</p><h3>What the warning is actually protecting you from</h3><p>When a value is captured by a Task closure, it crosses a <strong>concurrency domain boundary</strong> — it moves from one isolated context to another. Swift&#39;s concurrency system requires that any value crossing such a boundary conforms to Sendable, which guarantees it can be safely used across threads without causing a <strong>data race</strong>.</p><p>A data race occurs when two threads access the same memory simultaneously and at least one of them is writing. The consequences are not primarily about security — they are about <strong>correctness and stability</strong>: crashes, undefined behaviour, corrupted state, and results that change between runs in ways that are nearly impossible to debug.</p><p>Task { @MainActor in } makes the compiler enforce three things:</p><ul><li>The closure is @Sendable — values it captures must be safe to cross concurrency boundaries</li><li>The operation runs isolated on the @MainActor</li><li>Actor-isolation and Sendability rules are checked at compile time</li></ul><p>DispatchQueue.main.async enforces none of these at the compiler level.</p><h3>The correct fix: making the function async</h3><p>The clean solution is to make updateNotificationsReminder itself async, then call it with await from the outer Task:</p><pre>func updateNotificationsReminder(for people: People) async {<br>    removeNotificationsReminder(for: people)<br><br>    if people.isPresent == true {<br>        let success = await addNotificationsReminder(for: people)<br><br>        if !success {<br>            print(&quot;Update failure for notification: \(people.peopleId)&quot;)<br>        }<br>    }<br>}</pre><pre>Task { @MainActor [weak self] in<br>    guard let self else { return }<br>    await self.updateNotificationsReminder(for: people) // ✅ No warning<br>}</pre><p>Why does this resolve it? When updateNotificationsReminder is async and called with await inside a Task { @MainActor in } closure, the compiler can verify that people enters an @MainActor-isolated async context at a point where isolation is guaranteed. The @MainActor annotation is doing the isolation work — async alone is not sufficient, but it&#39;s what enables the function to be called correctly <em>from</em> an isolated context.</p><p>The original version also contained a Task { @MainActor in } nested inside the function. Since the rewritten function is already being called on the @MainActor, that inner Task is redundant and has been removed for clarity.</p><h3>The Core Data exception</h3><p>Conforming a type to Sendable is normally how you tell the compiler a value is safe to cross concurrency boundaries. For most types you control, this is straightforward.</p><p>Core Data NSManagedObject subclasses created with <strong>CodeGen: Class Definition</strong> are an exception. Because NSManagedObjectis not thread-safe, these classes cannot genuinely conform to Sendable.</p><p>The documented Apple workaround is @unchecked Sendable:</p><pre>extension People: @unchecked Sendable {}</pre><p>This tells the compiler to skip its Sendability checks for People. The trade-off is that you are taking manual responsibility for ensuring thread safety — you&#39;re not gaining safety, you&#39;re opting out of the compiler&#39;s verification. Use it as a bridge while migrating to SwiftData or a safer data-passing strategy, not as a permanent solution.</p><h3>Why actors make the guarantee structural</h3><p>The deepest fix isn’t suppressing warnings — it’s designing shared mutable state so that races are structurally impossible. That’s what actor provides.</p><p>Here’s a bank account where concurrent deposits and withdrawals are safe by construction:</p><pre>import SwiftUI<br><br>actor BankAccount {<br>    private var balance: Decimal<br><br>    init(initialBalance: Decimal) {<br>        self.balance = initialBalance<br>    }<br><br>    func deposit(_ amount: Decimal) {<br>        guard amount &gt; 0 else { return }<br>        balance += amount<br>        print(&quot;Deposited \(amount). Balance: \(balance)&quot;)<br>    }<br><br>    func withdraw(_ amount: Decimal) throws {<br>        guard amount &gt; 0 else { return }<br>        guard balance &gt;= amount else {<br>            throw BankError.insufficientFunds<br>        }<br>        balance -= amount<br>        print(&quot;Withdrew \(amount). Balance: \(balance)&quot;)<br>    }<br><br>    func currentBalance() -&gt; Decimal { balance }<br>}<br><br>enum BankError: Error {<br>    case insufficientFunds<br>}</pre><p>Running four concurrent operations against it:</p><pre>let account = BankAccount(initialBalance: 1000)<br><br>await withTaskGroup(of: Void.self) { group in<br>    group.addTask { await account.deposit(200) }<br>    group.addTask { try? await account.withdraw(150) }<br>    group.addTask { await account.deposit(50) }<br>    group.addTask { try? await account.withdraw(100) }<br>}<br><br>let finalBalance = await account.currentBalance()<br>print(&quot;Final balance: \(finalBalance)&quot;)<br>// Final balance: 1000.0  (starting 1000 + 200 + 50 - 150 - 100)</pre><p>The final balance is always correct, regardless of the order the tasks execute. The actor serialises access to balance — only one operation can read or write it at a time.</p><p>Now replace actor with class and run the same code. The guard balance &gt;= amount check and the balance -= amount write are no longer atomic. Two concurrent withdraw calls can both pass the guard before either has updated the balance — allowing a withdrawal that should have been rejected. The final balance becomes unpredictable, and on some runs the account goes negative. No compiler warning will tell you this is happening.</p><h3>When to use each</h3><p><strong>Use </strong><strong>DispatchQueue.main.async</strong> only when:</p><ul><li>You are working in Swift 5 compatibility mode on existing code that cannot be migrated immediately</li><li>The operation is purely UI-bound and you have verified (manually) that no shared mutable state is involved</li></ul><p><strong>Use Swift Concurrency (</strong><strong>Task, </strong><strong>async/await, </strong><strong>actor)</strong> when:</p><ul><li>Writing any new code</li><li>Targeting Swift 6 strict concurrency mode</li><li>Any shared mutable state is involved</li><li>You want the compiler to verify thread safety rather than relying on manual discipline</li></ul><p>The clearest signal that DispatchQueue is not the right tool is the warning itself. When Swift&#39;s concurrency system flags a Sendability violation, the correct response is to satisfy the compiler&#39;s requirement — not to switch to an API that doesn&#39;t check.</p><p><strong>Thank you for reading !</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab0b54f70fd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[struct View vs @ViewBuilder Function: When to Use Each in SwiftUI]]></title>
            <link>https://medium.com/@swifttoday/struct-view-vs-viewbuilder-function-when-to-use-each-in-swiftui-3105fb3a9ba8?source=rss-8f60b87c00e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3105fb3a9ba8</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[iphone-app-development]]></category>
            <dc:creator><![CDATA[SwiftToday]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 18:27:09 GMT</pubDate>
            <atom:updated>2026-06-05T18:27:09.274Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Swift · iOS &amp; macOS · SwiftUI</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uarFtM19PR2g5IHAsNioDg.png" /></figure><blockquote>TL;DR: SwiftUI gives you two ways to produce a view. You can declare a struct that conforms to View, or you can write a function annotated with @ViewBuilder. Both can render identical output on screen, and both use some View as their return type — so it&#39;s reasonable to wonder whether the choice matters at all.</blockquote><blockquote>It does. The difference isn’t visual; it’s about identity, ownership, and how SwiftUI tracks your UI over time.</blockquote><h3>Two ways to produce a View</h3><p>Here are both approaches side by side:</p><pre>// Approach 1: a struct conforming to View<br>struct MainView: View {<br>    var body: some View {<br>        VStack {<br>            Text(&quot;Hello, World!&quot;)<br>        }<br>    }<br>}<br><br>// Approach 2: a function annotated with @ViewBuilder<br>@ViewBuilder<br>func displayMainView() -&gt; some View {<br>    Text(&quot;Greetings!&quot;)<br>    Image(systemName: &quot;1.circle&quot;)<br>}</pre><p>Both produce a view. Both return some View. So what is some View actually doing, and why does @ViewBuilder exist?</p><h3>What some View means</h3><p>some View is an <strong>opaque return type</strong>. It tells the compiler: &quot;this returns one specific concrete type that conforms to View, but the caller doesn&#39;t need to know which one.&quot; It&#39;s a way of hiding implementation detail while keeping full type safety.</p><p>The constraint this creates is important: a function returning some View must return <strong>a single, unambiguous type</strong>. That constraint is what makes the following situation interesting.</p><h3>Why a plain function can’t return two views</h3><p>Consider these two functions — neither uses @ViewBuilder. Can you tell which one compiles?</p><pre>// Example 1<br>func displayMainView() -&gt; some View {<br>    Text(&quot;Greetings!&quot;)<br>    Image(systemName: &quot;1.circle&quot;)<br>}<br><br>// Example 2<br>func displayMainView() -&gt; some View {<br>    Text(&quot;Greetings!&quot;)<br>}</pre><p>Only the second compiles. In a regular Swift function, listing multiple expressions without return doesn&#39;t combine them — each line is a separate statement, and Swift can only implicitly return the last one. With two bare view expressions, the compiler can&#39;t determine a single return value and produces:</p><pre>Function declares an opaque return type, but has no<br>return statements in its body from which to infer an underlying type</pre><p>You can work around this by adding an explicit return on the last line:</p><pre>func displayMainView() -&gt; some View {<br>    Text(&quot;Greetings!&quot;)<br>    return Image(systemName: &quot;1.circle&quot;)<br>}</pre><p>But now only Image is returned — Text is simply ignored. That&#39;s not useful.</p><p>The other workaround is to wrap everything in a container:</p><pre>func displayMainView() -&gt; some View {<br>    VStack {<br>        Text(&quot;Greetings!&quot;)<br>        Image(systemName: &quot;1.circle&quot;)<br>    }<br>}</pre><p>That works for two elements. But as a layout grows, this quickly becomes impractical:</p><pre>func displayMainView() -&gt; some View {<br>    VStack {<br>        VStack {<br>            Text(&quot;Greetings!&quot;)<br>            Image(systemName: &quot;1.circle&quot;)<br>        }<br>        VStack {<br>            Text(&quot;A pleasure!&quot;)<br>        }<br>    }<br>}</pre><p>This is pure madness. And it gets worse from there.</p><h3>What @ViewBuilder actually is</h3><p>@ViewBuilder is a <strong>result builder</strong> — a Swift language feature that transforms a sequence of expressions in a function or closure body into a single composite value. It&#39;s not a macro. Result builders and macros are distinct Swift features; result builders work by applying a set of static build methods at compile time to combine multiple expressions into one.</p><p>@ViewBuilder specifically applies this to views. When you annotate a function with it, you can list multiple view expressions and they are combined automatically — no containers required, no explicit return, no guessing:</p><pre>@ViewBuilder<br>func displayMainView() -&gt; some View {<br>    VStack {<br>        Text(&quot;Greetings!&quot;)<br>        Image(systemName: &quot;1.circle&quot;)<br>    }<br><br>    VStack {<br>        Text(&quot;A pleasure!&quot;)<br>    }<br>}</pre><p>This is also exactly what makes SwiftUI’s var body: some View work. The body property is implicitly annotated with @ViewBuilder, which is why you can list views inside it freely. When you declare a struct conforming to View without implementing body, Xcode tells you:</p><pre>Type &#39;MainView&#39; does not conform to protocol &#39;View&#39;</pre><p>…because View requires a body property, and without it the @ViewBuilder result builder has nothing to work with.</p><h3>The real difference: identity in the view hierarchy</h3><p>The visual output of a struct view and a @ViewBuilder function can be identical. What differs is how they appear in SwiftUI&#39;s internal view graph.</p><p>Take these two implementations of a parent containing a child:</p><pre>// Using a struct<br>struct Parent: View {<br>    var body: some View {<br>        Child()<br>    }<br>}<br><br>struct Child: View {<br>    var body: some View {<br>        Text(&quot;Hello&quot;)<br>    }<br>}</pre><pre>// Using a @ViewBuilder function<br>struct Parent: View {<br>    @ViewBuilder<br>    func child() -&gt; some View {<br>        Text(&quot;Hello&quot;)<br>    }<br><br>    var body: some View {<br>        child()<br>    }<br>}</pre><p>In the view graph, these are not equivalent:</p><pre>// Struct version<br>Parent<br>  └─ Child<br>       └─ Text<br><br>// @ViewBuilder function version<br>Parent<br>  └─ Text</pre><p>When Child is a struct, SwiftUI assigns it a <strong>stable identity</strong> in the hierarchy. It can track that node independently, diff against it across rebuilds, and attach state to it. The @ViewBuilder function has no identity of its own — its output is inlined directly into Parent&#39;s node as if the function didn&#39;t exist. This is the root of every downstream difference between the two approaches.</p><h3>Why @State doesn’t work inside a @ViewBuilder function</h3><p>The inlining behaviour explains why state ownership works the way it does.</p><p>@State storage is attached to a specific <strong>view node</strong> in the hierarchy. When you declare @State inside a struct, SwiftUI knows exactly which node owns it, preserves it across rebuilds, and manages its lifetime tied to that node.</p><p>A @ViewBuilder function is not a view node. Its output is merged into the parent&#39;s node, and so any @State declared inside a function is treated as belonging to the parent view — not to the function. Since Swift 5.9 / iOS 17, the compiler will warn you about this directly:</p><pre>Accessing State&#39;s value outside of being installed on a View.<br>This will result in a constant Binding over time.</pre><p>In older Swift versions this could fail silently, producing no meaningful mutation and no working bindings. Either way, the behaviour is not what you’d expect from state declared in a standalone view.</p><p>The same principle applies to environment values, update boundaries, and previews: a @ViewBuilder function doesn&#39;t create a boundary, so nothing scoped to &quot;this view&quot; can attach to it.</p><h3>When to use each</h3><p><strong>Use a struct conforming to </strong><strong>View when the view:</strong></p><ul><li>Owns state (@State, @StateObject)</li><li>Needs a stable identity in the hierarchy</li><li>Should be independently previewable or testable</li><li>Is a reusable UI unit meant to be composed by other views</li></ul><p><strong>Use a </strong><strong>@ViewBuilder function when you need:</strong></p><ul><li>A local helper that assembles layout inline</li><li>A conditional layout without creating a separate file</li><li>A small, private composition that doesn’t need its own state or identity</li></ul><pre>// A good use of @ViewBuilder — a local conditional layout helper<br>@ViewBuilder<br>func content() -&gt; some View {<br>    if flag {<br>        FirstView()<br>    } else {<br>        SecondView()<br>    }<br>}</pre><p>The function here does one thing well: it makes a conditional decision and returns a view. It doesn’t need state, it doesn’t need an identity, and extracting it into a separate struct would be over-engineering.</p><h3>The decision in one sentence</h3><p>If the view owns something — state, identity, lifecycle — make it a struct. If it’s just an expression that assembles a layout, a @ViewBuilder function is the cleaner choice.</p><p><strong>Thank you for reading !</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3105fb3a9ba8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why @StateObject Exists When @ObservedObject Already Works]]></title>
            <link>https://medium.com/@swifttoday/why-stateobject-exists-when-observedobject-already-works-ab9791ef1884?source=rss-8f60b87c00e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab9791ef1884</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[SwiftToday]]></dc:creator>
            <pubDate>Fri, 29 May 2026 14:45:12 GMT</pubDate>
            <atom:updated>2026-05-29T14:45:12.311Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Swift 6.2 · iOS &amp; macOS · SwiftUI</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHQCsmUWmC3tlQQx8JW4IA.png" /></figure><blockquote>TL;DR: If you’ve used both @StateObject and @ObservedObject in SwiftUI, you might have noticed they look almost identical at the call site. Both observe a class that conforms to ObservableObject. Both trigger a view refresh when published properties change. So why does Swift need two separate property wrappers to do what feels like the same job?</blockquote><blockquote>The answer is about ownership — specifically, <em>who</em> is responsible for keeping an object alive.</blockquote><h3>Property wrappers, briefly</h3><p>Both @StateObject and @ObservedObject are <strong>property wrappers</strong> — a Swift feature that lets a declaration automatically gain pre-built behaviour. When you write:</p><pre>@State private var count: Int = 0</pre><p>…you’re not just storing an integer. The @State wrapper gives SwiftUI the ability to watch that value and rebuild the view when it changes, all wired up automatically at the point of declaration. @StateObject and @ObservedObject work on the same principle, but for reference-type objects rather than simple values.</p><h3>The foundation: ObservableObject</h3><p>Before either wrapper is useful, the class you want to observe must conform to ObservableObject:</p><pre>class CounterVM: ObservableObject {<br>    @Published var count = 0<br>}</pre><p>ObservableObject is the protocol that gives a class the ability to broadcast changes to any view that is watching it. The @Published property wrapper marks which properties trigger those broadcasts. Without ObservableObject, neither @StateObjectnor @ObservedObject has anything to work with.</p><h3>What @ObservedObject does — and where it falls short</h3><p>@ObservedObject does exactly what its name says: it observes an object. When any @Published property on that object changes, the view re-renders to reflect the new state.</p><pre>struct CounterView: View {<br>    @ObservedObject var vm: CounterVM<br><br>    var body: some View {<br>        Button(&quot;Count: \(vm.count)&quot;) {<br>            vm.count += 1<br>        }<br>    }<br>}</pre><p>Used this way — where the object is <em>passed in</em> from outside — @ObservedObject works correctly and is exactly the right tool.</p><p>The problem appears when developers instantiate the object <em>inside</em> the view:</p><pre>struct CounterView: View {<br>    @ObservedObject var vm = CounterVM() // ⚠️ Dangerous<br><br>    var body: some View {<br>        Button(&quot;Count: \(vm.count)&quot;) {<br>            vm.count += 1<br>        }<br>    }<br>}</pre><p>SwiftUI rebuilds the view struct every time its state changes — that is the engine that drives reactive UI. When a view is rebuilt and its initialiser runs again, CounterVM() is called again, creating a <strong>fresh instance</strong> of the object. The previous instance, and all of its state, is discarded. The object is not copied — it is replaced.</p><p>The consequences of this are significant:</p><ul><li>State resets unexpectedly</li><li>Network requests restart on every rebuild</li><li>Subscriptions duplicate or drop</li><li>Objects are repeatedly allocated and deallocated</li></ul><p>@ObservedObject is not designed to prevent this. Its job is to observe — not to manage the lifetime of what it observes.</p><h3>What @StateObject does differently</h3><p>@StateObject solves the ownership problem. When you declare a property with @StateObject, SwiftUI initialises that object <strong>exactly once</strong> — when the view first appears in the hierarchy — and retains it for as long as the view remains in the hierarchy. Subsequent rebuilds of the view struct do not reinitialise the object.</p><pre>struct CounterView: View {<br>    @StateObject private var vm = CounterVM() // ✅ Created once, retained<br><br>    var body: some View {<br>        Button(&quot;Count: \(vm.count)&quot;) {<br>            vm.count += 1<br>        }<br>    }<br>}</pre><p>The rule that follows from this is clear:</p><blockquote><strong><em>Use </em></strong><strong><em>@StateObject where the object is born. Use </em></strong><strong><em>@ObservedObject everywhere else.</em></strong></blockquote><p>If a view <em>creates</em> the object, it should declare it with @StateObject. If a view <em>receives</em> the object from a parent (via initialiser, @EnvironmentObject, or another mechanism), it should declare it with @ObservedObject.</p><p>A typical parent-child pattern looks like this:</p><pre>// Parent — owns and creates the object<br>struct ParentView: View {<br>    @StateObject private var vm = CounterVM()<br><br>    var body: some View {<br>        ChildView(vm: vm)<br>    }<br>}<br><br>// Child — observes the object it received<br>struct ChildView: View {<br>    @ObservedObject var vm: CounterVM<br><br>    var body: some View {<br>        Text(&quot;\(vm.count)&quot;)<br>    }<br>}</pre><p>The parent is responsible for the object’s lifetime. The child just watches it.</p><h3>Why not combine them into one wrapper?</h3><p>It’s a reasonable question. The answer comes down to what SwiftUI needs to know about every object in the view hierarchy:</p><ol><li><strong>Should this object be created here, or received from elsewhere?</strong></li><li><strong>Who is responsible for keeping it alive?</strong></li><li><strong>Should it survive this view being rebuilt?</strong></li></ol><p>If a single wrapper tried to handle both roles, SwiftUI would have no way to answer these questions unambiguously. In a parent-child view tree, if both parent and child declared the same object with a combined wrapper, the runtime would need to guess which one owns the object. Ownership ambiguity leads to two failure modes: the object being released too early (lost state), or kept alive longer than necessary (memory leaks).</p><p>The split between @StateObject and @ObservedObject is SwiftUI&#39;s way of making ownership explicit and unambiguous. Apple separated the responsibilities deliberately — the two wrappers aren&#39;t redundant, they&#39;re complementary.</p><h3>In summary</h3><pre>Wrapper            Creates          Owns        Use when<br>                   the              the <br>                   object           lifecycle<br>----------------------------------------------------------------------------<br>@StateObject       Yes              Yes        You are instantiating<br>                   once only                   the object in this view<br>----------------------------------------------------------------------------<br>@ObservedObject    No               No         The object comes from<br>                                               a parent or external source</pre><p>If you take one thing away from this: @ObservedObject is not safe for objects you instantiate inside the view. That&#39;s not what it was built for. @StateObject is the declaration that tells SwiftUI: <em>this object belongs to me, keep it alive.</em></p><p><strong>Thank you for reading !</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab9791ef1884" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>