<?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 Scheutz David on Medium]]></title>
        <description><![CDATA[Stories by Scheutz David on Medium]]></description>
        <link>https://medium.com/@scheutz.david?source=rss-465318195290------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IaBvRk4apcRShCsf-p7Uew.png</url>
            <title>Stories by Scheutz David on Medium</title>
            <link>https://medium.com/@scheutz.david?source=rss-465318195290------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 04:58:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@scheutz.david/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[Copy Immutable Structs in Swift]]></title>
            <link>https://medium.com/@scheutz.david/copy-immutable-structs-in-swift-2bd4e757eebb?source=rss-465318195290------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bd4e757eebb</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[codegen]]></category>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[stencil]]></category>
            <category><![CDATA[struct]]></category>
            <dc:creator><![CDATA[Scheutz David]]></dc:creator>
            <pubDate>Sat, 30 Nov 2024 14:55:43 GMT</pubDate>
            <atom:updated>2024-11-30T14:55:43.047Z</atom:updated>
            <content:encoded><![CDATA[<p>TLDR: Using code generation to add copy functionality to structs in Swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S3NbwHayzYSL76-T" /><figcaption>Photo by <a href="https://unsplash.com/@joshappel?utm_source=medium&amp;utm_medium=referral">Josh Appel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Intro</h4><p>One of the core aspects of any app architecture is handling data and propagating changes throughout the system.</p><p>In general, a good advice is to stick with immutability as it will simplify development and reduce potential bugs, more about that in a moment. However, engineers with a Kotlin background know that copying an immutable model in Swift isn’t as straightforward as expected.</p><p>In this article, we’ll briefly explore why immutability matters and demonstrate how to make your Swift development experience more convenient.</p><h4>Mutable Structs — The Anti-Pattern</h4><p>Most likely throughout your career you’ve encountered models like this:</p><pre>struct User {<br>  let id: String<br>  var name: String<br>}<br><br>var user = User(id: &quot;1&quot;, name: &quot;Dave&quot;)<br>user.name = &quot;Changed&quot; // update</pre><p>or slightly improved variations like this:</p><pre>struct User {<br>  let id: String<br>  private(set) var name: String<br><br>  mutating func update(name: String) {<br>    self.name = name<br>  }<br>}<br><br>var user = User(id: &quot;1&quot;, name: &quot;Dave&quot;)<br>user.update(name: &quot;Changed&quot;) // more explicit update</pre><p><strong>So, what’s the issue?</strong><br>Swift encourages immutability and functional programming paradigms for safer and more predictable code. Mutable structs conflict with these principles, making them less idiomatic in modern Swift.</p><p>Moreover, mutable structs compromise value semantics. Since structs are value types, they are copied when passed around. For example, modifying a copy won’t affect the original, which can lead to unexpected behavior if developers mistakenly expect reference-like behavior.</p><p>While mutable structs aren’t inherently bad, they should be used deliberately and with caution to avoid unintended side effects.</p><h4>Immutability — and it’s Challenges</h4><p>Immutability helps preventing <em>race conditions</em>, ensures thread safety without explicit synchronization, and simplifies <em>state management</em> by enforcing clear transitions between states. It also makes it easier to reason about the behavior of your code.</p><p>However, if you’ve ever worked with immutable structs, you’ve likely experienced how cumbersome updates can be:</p><pre>struct User {<br>  let id: String<br>  let name: String<br>}<br><br>let user = User(id: &quot;1&quot;, name: &quot;Dave&quot;)<br>let updatedUser = User(id: user.id, name: &quot;Changed&quot;) // tedious update</pre><p>The common <a href="https://stackoverflow.com/questions/50321336/how-can-i-easily-copy-an-immutable-struct-in-swift-varying-only-some-fields-li">answer</a> you’ll find on <strong>Stackoverflow</strong> is to create a <br>custom copy method:</p><pre>extension User {<br>    func copy(id: String? = nil, name: String? = nil) -&gt; Self {<br>        .init(id: id ?? self.id, name: name ?? self.name)<br>    }<br>}<br><br>let user = User(id: &quot;1&quot;, name: &quot;Dave&quot;)<br>let updatedUser = user.copy(name: &quot;Changed&quot;) // looks neat!</pre><p>While this approach needs change to support optional types, I wasn’t thrilled about writing repetitive boilerplate code for all my models.</p><p>During my search for better solutions, I came across <a href="https://github.com/rayeddev/swift-immutable"><strong>swift-immutable</strong></a>. <br>This neat library, created by <a href="https://github.com/rayeddev"><strong>Rayed AL-Nom</strong></a>, uses a <em>Swift Macro</em> to extend structs with a clone method.</p><p>After giving it a try, I noticed two critical limitations:<br> ❌ no support for <em>optional data types</em><br> ❌ no support for structs with <em>custom</em> <em>initializers</em></p><p>To be fair, the project is relatively new, and I’m optimistic these issues will be addressed in the future!</p><p>Given my experience with code generation using <a href="https://github.com/stencilproject/Stencil">Stencil</a> and the limited time to explore Swift Macros in depth, I decided to create a Xcode build tool plugin: <a href="https://github.com/davidscheutz/SwiftCopy"><strong>SwiftCopy</strong></a>.</p><h4>SwiftCopy — Immutability Made Easy</h4><p><a href="https://github.com/davidscheutz/SwiftCopy">GitHub - davidscheutz/SwiftCopy: Copy functionality for immutable Swift structs using code generation</a></p><p>The framework generates a copy method for all structs conforming to the Copyable protocol. It supports optional data types and structs with custom initializers:</p><pre>import SwiftCopy<br><br>struct User: Copyable {<br>  let id: String<br>  let name: String<br>  let lastOnline: Date?<br><br>  init(name: String, lastOnline: Date? = nil) {<br>    self.id = UUID().uuidString<br>    self.name = name<br>    self.lastOnline = lastOnline<br>  }<br>}<br><br>let user = User(name: &quot;Dave&quot;)<br>_ = user.copy(name: &quot;Changed&quot;)                // update name<br>_ = user.copy(lastOnline: .update(Date.now))  // assign current date<br>_ = user.copy(lastOnline: .reset)             // assign nil</pre><p>In addition, <a href="https://github.com/davidscheutz/SwiftCopy">SwiftCopy</a> generates Builder and Updater objects, which provide a safe and convenient way to construct and update your models:</p><pre>let newUser = User.Builder()<br>    .with(name: &quot;New&quot;)<br>    .build()</pre><pre>let updater = user.updater() // created using an existing user<br><br>updater.name = &quot;Changed&quot;<br>updater.lastOnline = .now<br><br>let updatedUser = updater.build()</pre><p>For more details on how it works, feel free to check out the <a href="https://github.com/davidscheutz/SwiftCopy/blob/master/README.md">README</a> or the demo project in the repository.</p><p><strong>Disclaimer</strong>: I certainly would prefer to use a Swift Macro instead of a build tool plugin, as an annotation feels like a better fight compared to the protocol usage and it would reduce the app bundle size. However, due to time constraints, I chose to use tools I’m more familiar with 🙄.</p><h4>Conclusion</h4><p>Designing APIs that simplify state mutation while maintaining a well defined data flow can be a challenging task. It often involves balancing tradeoffs between correctness and convenience.</p><p>The goal of this project was to avoid compromise and achieve both. This solution is part of a larger, more comprehensive architecture that I plan to write about and share more in the future. Personally, it’s been a highly rewarding experience so far, and I believe applying the above will help you avoid many common bugs and challenges.</p><p>What do you think?<br>Will you give it a try?<br>How do you currently handle state mutation?</p><p>I’d love to hear your thoughts, questions, and feedback. Let me know in the comments!</p><p>Thanks for reading! 🚀</p><p>PS: Follow me for more insights on building with excellence in Swift.<br>PPS: Happy to connect on LinkedIn: <a href="https://www.linkedin.com/in/david-scheutz-192334157/">David Scheutz</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bd4e757eebb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>