<?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 Juan Colilla on Medium]]></title>
        <description><![CDATA[Stories by Juan Colilla on Medium]]></description>
        <link>https://medium.com/@juancolilla_66813?source=rss-ee11ac4cf3ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EgzPHQqcf4ecmaGoexEeAQ@2x.jpeg</url>
            <title>Stories by Juan Colilla on Medium</title>
            <link>https://medium.com/@juancolilla_66813?source=rss-ee11ac4cf3ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:24:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@juancolilla_66813/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[Why your AI workflow shouldn't belong to any vendor.]]></title>
            <link>https://medium.com/@juancolilla_66813/why-your-ai-workflow-shouldnt-belong-to-any-vendor-48cc1eb2c99a?source=rss-ee11ac4cf3ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/48cc1eb2c99a</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[ai-tools]]></category>
            <dc:creator><![CDATA[Juan Colilla]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 11:52:46 GMT</pubDate>
            <atom:updated>2026-05-05T09:23:39.761Z</atom:updated>
            <content:encoded><![CDATA[<h3>Your AI workflow shouldn’t obey to a vendor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-IHR1eDuzfTmnrl8nMFBuw.png" /></figure><p>Strong LLMs and agentic CLI tools are everywhere now. That’s the part everyone celebrates. The part nobody talks about is how much of a professional’s time ends up going into the <strong>workflow and tooling </strong>instead of the work.</p><p>I’ve spent the last few months refining my AI coding workflow around Claude Code. I still pay for it, and I still think it’s the best agentic tool I’ve used for the kind of work I do. But the recent trajectory is hard to ignore: tighter limits on the affordable plans, recurring price hikes, Claude Code being pulled out of the cheaper tier altogether. That isn’t what democratising AI looks like — it’s the opposite.</p><p>Meanwhile, open-weight models keep getting more capable, and the hardware to run them locally is within reach for a lot of professionals. I’ve got my eye on an M5 Max for exactly this reason:</p><p>I want to put tools like Hermes Agent and OpenCode, paired with open models like Qwen, through real work — not toy benchmarks. They should compete on their own merits, not lose by default because nobody bothered to wire them into a serious workflow.</p><p>So I rebuilt mine, from scratch, on top of open standards.</p><h3>The point of being agnostic</h3><p>The whole system is built around one rule: <strong>your way of working shouldn’t depend on which subscription you’re paying this month.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTf-OqQSP19dfE2e46DEVw.png" /></figure><p>That has practical consequences I care about:</p><ul><li><strong>Mix and match instead of locking in.</strong> Three €20 plans across different vendors can be more useful for me than one €100 plan that holds my workflow hostage, for example. Every agent reads the same contract and pulls from the same shared skill drawer.</li><li><strong>Local AI as a first-class citizen.</strong> The day I run Qwen3.6 or Gemma4 on my own hardware, it plays by the same rules as the cloud agents — same skills, same conventions, same project knowledge. No “local model second-class citizen” problem. Unlimited tokens for the less demanding tasks, premium tools where they actually pay off.</li><li><strong>Teams stop fighting over tooling.</strong> Every member can pick the agent that fits them — Claude Code, Cursor, a local OpenCode setup, whatever — while the project itself enforces a single shared framework. Designers can adopt it without friction too: `DESIGN.md` is theirs as much as the engineers’.</li></ul><p>I’m not reinventing anything here. I’m assembling a car out of pieces the community is already publishing. The standards exist; my job was to glue them together cleanly.</p><h3>Three standards, one contract</h3><p>The system rests on three open specs: <a href="https://agents.md/"><strong>AGENTS.md</strong></a> (donated by OpenAI to the Linux Foundation in December 2025), <a href="https://agentskills.io/specification"><strong>agentskills.io</strong></a><strong> </strong>(Anthropic, multi-vendor adoption), and <a href="https://github.com/google-labs-code/design.md"><strong>DESIGN.md</strong></a> (Google Stitch).</p><p>Almost every agent worth using already speaks at least one of them.</p><p>For the few that don’t, the answer is a <strong>3-line adapter file</strong> — never a parallel set of rules. That distinction matters. An adapter is a redirect, not a rewrite. The moment you start putting real rules inside an adapter, you’re back to vendor lock-in with extra steps.</p><p>What about the genuinely useful tool-specific features? The standards already include a clean answer: `x-&lt;tool&gt;:` namespaces inside the frontmatter. If Claude has skills nobody else has, wire them up in the namespace; other tools simply ignore the bits they can’t use. You get the unique strengths of each tool without giving up portability — the adapter pattern is what unlocks tool-by-tool advantages <em>without </em>breaking the standard.</p><h3>Knowledge that stays readable</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Acrqjm5OM_gkjbyid0c2Q.png" /></figure><p>The other half of the workflow is what the agents read once they’re plugged in.</p><ul><li>`<a href="https://matklad.github.io/2021/02/06/ARCHITECTURE.md.html"><strong>ARCHITECTURE.md</strong></a>` carries the architectural rules of the project, plus the history of when those rules were broken and why. Tripping twice on the same stone is the kind of thing AI agents are remarkably good at if you let them — so I don’t.</li><li>`<a href="https://github.com/google-labs-code/design.md"><strong>DESIGN.md</strong></a>` holds the design system and tokens. Authored and maintained by the design team, consumed by every agent on the project.</li></ul><p>On top of that lives a <strong>self-maintained knowledge library</strong> — investigations, decisions, planning notes — indexed with predictable headers so any agent can jump straight into the bit it needs without re-reading the whole tree. That alone saves a brutal amount of input tokens, and it stops research from being repeated three times by three different agents on three different days. It also means the next person onboarding into the project (or me, six months from now) can read the <em>why</em>, not just the <em>what</em>.</p><h3>What I’m releasing today</h3><p>The <strong>Agentic Agnostic Workflow Environment</strong>, v0.1, Apache 2.0, on GitHub.</p><p>It ships as two skills:</p><ul><li>`<strong>bootstrap</strong>` stands the whole environment up from any agent that can run skills, migrating whatever you already had.</li><li>`<strong>doctor</strong>` keeps the environment from drifting after months of real use.</li></ul><p>The README covers the technical detail. This post is just the <strong>why</strong>.</p><h3>Take it</h3><p>v0.1 is the first public release, not the final word. Adapters for tools I haven’t covered, skills that respect the conventions, refinements from teams using it in anger — all welcome. The only thing I ask is to keep the spirit: single source of truth, no vendor lock-in, no proprietary extensions sneaking back into the open spec.</p><p>That’s the freedom this project is after.</p><p><strong>Repo: </strong><a href="https://github.com/JuanColilla/Agentic-Agnostic-Workflow-Environment">https://github.com/JuanColilla/Agentic-Agnostic-Workflow-Environment</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48cc1eb2c99a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Three-Body Problem — How I built a social health app with zero server costs]]></title>
            <link>https://medium.com/@juancolilla_66813/the-three-body-problem-how-i-built-a-social-health-app-with-zero-server-costs-1fe071e9d96e?source=rss-ee11ac4cf3ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fe071e9d96e</guid>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[cloudkit]]></category>
            <category><![CDATA[indiedev]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Juan Colilla]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 17:07:02 GMT</pubDate>
            <atom:updated>2026-03-11T17:16:48.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Article header showing the title ‘The Three-Body Problem: How I built a social health app with zero server costs using CloudKit’ with three orbital dots representing the Private, Shared, and Public databases on a dark background." src="https://cdn-images-1.medium.com/max/1024/1*u2-E3thWgjHOSczi7kENOQ.png" /></figure><p>As an app engineer, there’s always been one thing that stopped me from shipping side projects: server infrastructure.</p><p>We have lots of free-tier options out there — Supabase, Firebase, you name it. But they all require setup, maintenance, privacy tradeoffs, and if your app doesn’t get initial traction, the server can go down silently, leaving new users staring at a loading spinner. For an indie developer, paying for a backend that might serve five people feels like renting an office for a lemonade stand.</p><p>So when I started building <strong>Poolendar </strong>— a gut-health tracking app — I made myself a promise: no servers. Not “cheap servers.” Not “serverless functions.” Zero. Nada. And somehow, I pulled it off.</p><h3>Wait, a poo tracking app?</h3><p>Yeah, as gross as it sounds.</p><p>My rule when starting a new project is simple: the product has to be useful to <em>me</em>. If it helps me, I already won. If it helps more people, even better.</p><p>Poolendar is built for people with IBS, IBD, Crohn’s, or any other gut-related condition. You track your events, log what you ate, and an on-device AI helps you spot patterns and correlations. You can even export a clinical PDF for your doctor — reducing visits and getting to a diagnosis faster.</p><p>But I wanted it to be more than just another health tracker. It needed something <em>fun</em>, something <em>rebel</em>.</p><p>Here’s what I noticed: in Spain, it’s gone viral that groups of friends create WhatsApp groups to report when they go to the bathroom, making a ranking at the end of the month as a competition. It sounds ridiculous, and it is. But it’s also brilliant, because it does something powerful — it breaks a taboo.</p><p>Talking about poo and gut-related events isn’t pleasant. It’s not even considered polite. But for millions of people suffering from functional disorders or immune diseases, that taboo is a barrier to getting help. A silly ranking among friends can crack that wall open.</p><p>So Poolendar needed a Social component. But how? How do you build social features that don’t empty your pocket, work reliably, keep user privacy (because this is still a health app with deeply intimate data), and support everything you need — rankings, private groups, insights?</p><p>That’s where the three-body system enters the game.</p><h3>The three bodies of iCloud</h3><figure><img alt="Diagram of three CloudKit databases. Private DB stores BowelEvent with optional fields synced via SwiftData. Shared DB stores CompetitionGroup, GroupMembership, and minimal SharedEvent. Public DB stores UserProfile with ownerRecordName. Data flow shows full events stripped to type and timestamp for rankings." src="https://cdn-images-1.medium.com/max/1024/1*35uyKsV4XVMLVr8EgR3zvQ.png" /></figure><p>iCloud isn’t just “the cloud.” It has three distinct database layers, each with different ownership, visibility, and quota rules. Understanding these three layers — and how they interact — is what made the entire architecture possible.</p><h4>Body #1: The Private Database</h4><p>This is the user’s own copy of your app’s database, stored in <em>their</em> iCloud account quota. It persists even if they delete the app, and syncs across all their devices automatically.</p><p>In Poolendar, this is where <strong>all</strong> health data lives. Every bowel movement, every flatulence event, every food log, every discomfort rating. Fully in control of the user, away from anyone else’s eyes.</p><p>The magic? How ridiculously simple it is to set up. SwiftData, Apple’s modern persistence framework, does all the heavy lifting. You configure your `ModelContainer` with a CloudKit database reference, and that’s it. Seriously, that’s it:</p><pre>let configuration = ModelConfiguration(<br>groupContainer: .identifier(&quot;REDACTED&quot;),<br>cloudKitDatabase: .private(&quot;REDACTED&quot;)<br>)<br>let container = try ModelContainer(for: schema, configurations: configuration)</pre><p>From this point on, every `@Query` and every `context.insert()` in your SwiftUI views is automatically mirrored to CloudKit. No sync code, no manual push/pull, no conflict resolution logic. SwiftData handles offline-to-online reconciliation using a last-write-wins merge policy, and monitors network connectivity transparently.</p><p>One important nuance: SwiftData’s automatic sync only works with the Private Database. There’s no `ModelConfiguration` option for syncing to the Shared or Public databases. That’s why Poolendar uses SwiftData for personal health data (where auto-sync is magic), but drops down to raw CloudKit operations for the social features. Two layers of persistence, one app.</p><pre>@Query var events: [BowelEvent] // Auto-synced across devices<br>context.insert(newEvent) // Automatically pushed to iCloud</pre><p>The only extra piece I built was a `CloudKitSyncMonitor` — an `@Observable` class that listens to iCloud account changes and exposes a simple state (`.synced`, `.syncing`, `.unavailable`, `.error`) so the UI can inform the user if something goes wrong. But even that is optional — without it, everything still syncs.</p><p>If CloudKit fails at container creation (corrupted store, iCloud signed out), the app falls back to an in-memory store and warns the user. Data is never lost; it just waits.</p><h4>Body #2: The Shared Database</h4><p>This is the layer Apple uses to share Notes and collaborate on documents in Pages — and so can you. This database is also stored in the user’s quota, but only in the <strong>owner’s</strong>. The owner can invite others and manage their permissions to read and/or write.</p><p>This is how Social Groups work in Poolendar.</p><p>When a user creates a group, the app doesn’t just create a record — it creates an entire private `CKRecordZone` in the creator’s Private Database, then shares it via a zone-wide `CKShare`:</p><pre>let groupID = UUID().uuidString<br>let zoneName = &quot;Zone_\(groupID)&quot;<br>// 1. Create a dedicated zone in the creator&#39;s Private DB<br>_ = try await cloudKit.createSharedZone(zoneName: zoneName)<br>// 2. Create a zone-wide CKShare (all participants can read &amp; write)<br>let share = CKShare(recordZoneID: zoneID)<br>share.publicPermission = .readWrite<br>// 3. Save group + share atomically<br>let operation = CKModifyRecordsOperation(recordsToSave: [groupRecord, share])<br>operation.isAtomic = true</pre><p>This zone contains three record types: `CompetitionGroup` (the group metadata), `GroupMembership` (one per member, with roles and soft-delete), and `SharedEvent` (the minimal ranking data).</p><p>Here’s the critical architectural decision: the creator sees the zone through `privateDatabase`, while invited members see it through `sharedDatabase`. Same data, different database path:</p><pre>func databaseForZone(_ zoneID: CKRecordZone.ID) -&gt; CKDatabase {<br>  if zoneID.ownerName == CKCurrentUserDefaultName {<br>  return container.privateCloudDatabase // I created this zone<br>  } else {<br>    return container.sharedCloudDatabase // I was invited to this zone <br>  }<br>}</pre><p>Invitations work through the native iOS `CKShare` URL. The creator gets a share URL, sends it via any channel — WhatsApp, iMessage, whatever. When the recipient opens it, iOS calls `userDidAcceptCloudKitShareWith`, and the app joins them to the zone. By my own choice and to keep things in control, I decided that max of 25 members per group, and max of 1 group per user.</p><p><strong>But what about privacy?</strong></p><p>This is the key decision. The `SharedEvent` record that goes into the shared zone is intentionally minimal:</p><pre>public struct SharedEvent: Codable, Identifiable, Sendable {<br>public let id: String<br>public let userID: String<br>public let eventType: String // &quot;bowelMovement&quot; or &quot;flatulence&quot;<br>public let timestamp: Date<br>// That&#39;s it. No consistency, no color, no urgency, no discomfort.<br>// Not a single byte of health detail leaves the Private Database.<br>}</pre><p>Poolendar cleans every detail and sends only the numbers needed to make the ranking. Not a single byte more.</p><p><strong>The potential issues I had to face</strong></p><p>What happens when the group owner deletes the app?</p><p>The zone lives on in their iCloud account — they didn’t delete the zone, just the app. If they reinstall, the app recovers the zone by scanning all private zones matching the `Zone_*` prefix. But if they go to iCloud settings and delete the data? The zone is gone. All members get a `.zoneNotFound` error:</p><pre>} catch let error as CKError<br>where error.code == .zoneNotFound || error.code == .unknownItem {<br>groupLostReason = .deletedByOwner<br>clearGroupState()<br>}</pre><p>Members are notified, local state is cleaned up, and they can create or join a new group. No orphaned data, no zombie groups.</p><p>Other edge cases I had to solve: duplicate memberships (CloudKit sync delay can cause double-writes — the app auto-deduplicates keeping the most recent active one), re-joins (soft-deleted memberships get reactivated instead of creating new records), and orphaned `SharedEvents` (a monthly purge-and-resync mechanism reconciles local events against remote records using deterministic record IDs: `”\(userID)-\(localEventID)”`).</p><h4>Body #3: The Public Database</h4><p>The third body, and the one that relies on the developer account. This database is accessible by everyone using the app — no permissions needed — and it runs on the <strong>10 GB of “free” storage</strong> included in your Apple Developer Program membership ($99/year).</p><p>Poolendar uses the Public Database for one thing: user profiles for the Social feature. And here’s the interesting part — they don’t require a login or registration. Users just create an identity (unique nickname + emoji or photo) and it gets tied to their Apple account. No Sign In with Apple, no email, no password, nothing.</p><p>Every profile is anchored to an `ownerRecordName` — an opaque, immutable identifier assigned by Apple to each iCloud account. You can’t fake it. You can’t change it. It survives app reinstalls, device changes, and iOS updates:</p><pre>let userRecordID = try await cloudKit.fetchCurrentUserRecordID()<br>let profile = UserProfile(<br>id: UUID().uuidString,<br>ownerRecordName: userRecordID.recordName, // Apple-assigned, immutable<br>displayName: &quot;GutWarrior&quot;,<br>avatarEmoji: &quot;💩&quot;,<br>// …<br>)</pre><p>No personal information is stored here (unless the user decides to use their real name or photo). Not a single health event, not a single piece of sensitive data.</p><p><strong>The math that makes it work</strong></p><p>Let me put those 10 GB into perspective with real numbers.</p><p>A `UserProfile` without a photo weighs roughly 0.5–1 KB — just strings, timestamps, and a couple of flags. With a photo, I cap it at 1.5 MB using a recursive JPEG compressor function that reduces quality from 0.9 to 0.1, then halves dimensions until it fits:</p><pre>static func compress(_ data: Data, maxBytes: Int = 1_500_000) -&gt; Data? {<br>guard let data = image.jpegData(compressionQuality: quality) else { return nil }<br>if data.count &lt;= maxBytes { return data }<br>if quality &gt; 0.1 {<br>return compressImage(image, maxBytes: maxBytes, quality: quality - 0.1)<br>}<br>// Quality exhausted - halve dimensions and retry<br>let newSize = CGSize(width: image.size.width / 2, height: image.size.height / 2)<br>// …<br>}</pre><p>Worst case — every user uploads a max-size photo — 1.5 MB per profile means ~6,600 users in 10 GB. But that’s the absolute worst case. In practice, most photos compress well below 500 KB, and many users just pick an emoji.</p><p>Realistic case (~300 KB average photo): <strong>~33,000 users</strong> before you’d worry. Emoji-only: <strong>~10 million profiles</strong> in those 10 GB.</p><p>For an indie app? 10 GB is a lot of runway. And if you keep your profiles light — emoji avatars instead of photos, 20-character display names — you’re looking at millions of profiles before you’d even think about storage. By the time you’re bumping against that ceiling, you have a business that can afford to think about it.</p><p>For an indie app, those numbers are more than enough to validate your product before server costs become a real conversation.</p><blockquote>“But wait — if there’s no server, how do you validate subscriptions?”</blockquote><p>You don’t need one. StoreKit 2 handles this on-device.</p><p>Every in-app purchase and subscription goes through Apple’s servers. StoreKit 2 provides cryptographically signed transactions that you can verify locally — no backend required. Although faking signatures is not impossible, it is not easy. The validation is real, it’s just not <em>yours</em> to maintain.</p><p>Poolendar uses RevenueCat on top of StoreKit to manage entitlements like groups, AI features and PDF reports. RevenueCat abstracts the subscription lifecycle — renewals, expirations, grace periods — so the app just asks &quot;is this user subscribed?&quot; and gets a reliable answer.</p><p>The interesting trick is how subscriptions survive reinstalls without a login screen. Remember that ownerRecordName from the Public Database? The profile&#39;s UUID doubles as the RevenueCat App User ID. When a user creates a profile, the app calls Purchases.shared.logIn(profile.id), linking their subscription to their CloudKit identity. On reinstall, the app finds the profile by ownerRecordName and logs back into RevenueCat with the same UUID:</p><pre>// On app launch — automatic recovery<br>if let profile = try? await fetchCurrentUserProfile() {<br>    try? await Purchases.shared.logIn(profile.id)<br>    // Subscription restored. No login screen. No &quot;restore purchases&quot; button.<br>}</pre><h4>Three bodies, one system</h4><figure><img alt="Swim lane diagram in three phases. Phase 1: Creator creates a CKRecordZone and zone-wide CKShare. Phase 2: Member opens share URL and joins via sharedDatabase. Phase 3: Events logged with full detail to Private DB, stripped to type and timestamp for Shared DB rankings. Privacy callout confirms health details never leave Private DB." src="https://cdn-images-1.medium.com/max/1024/1*DUZvHfIipEo2GhggscqG7Q.png" /></figure><p>The three-body problem in physics is famously unsolvable — three gravitational bodies in chaotic, unpredictable orbits. But in CloudKit, the three bodies aren’t chaotic. They’re complementary.</p><p><strong>Private Database</strong> keeps your users’ most sensitive data exactly where it should be — in their hands. Synced, encrypted, invisible to you.</p><p><strong>Shared Database</strong> enables social features without a backend, using iCloud’s own sharing infrastructure. The owner pays with their quota. Members contribute nothing. Privacy is preserved by design, not by policy.</p><p><strong>Public Database</strong> gives you a “free”, scalable identity layer. No authentication server, no user accounts, no passwords to leak.</p><p>Together, they gave Poolendar a fully functional social health app with rankings, private groups, subscription management, and clinical-grade privacy — all running on infrastructure that costs me exactly <strong>$0/month</strong>.</p><p>The $99/year Apple Developer fee? I was paying that anyway.</p><p>If you’re an indie developer sitting on a social feature idea, thinking “I can’t afford the backend,” maybe you can’t afford <em>not</em> to look at what Apple already gave you.</p><p><a href="https://apps.apple.com/app/poolendar/id6757929768">Poolendar is available on the App Store</a></p><blockquote>If you suffer from a gut condition, or if you just want to compete with your friends on who visits the bathroom more — we don’t judge.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fe071e9d96e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My take on AI as an iOS Engineer]]></title>
            <link>https://medium.com/@juancolilla_66813/my-take-on-ai-as-an-ios-engineer-90777ede9e2b?source=rss-ee11ac4cf3ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/90777ede9e2b</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[future]]></category>
            <category><![CDATA[work]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Juan Colilla]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 03:43:29 GMT</pubDate>
            <atom:updated>2026-02-12T03:43:29.435Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NnBNm3xBPau_CszDUdLS6g.png" /></figure><p>Since the day ChatGPT was released as a chatbot experience with a non-expected success, AI has turned from a techie term into a hugely widespread consumer product.</p><p>Since then, and with every new version of GPT, developers have been using it to generate boilerplate code, sometimes and some devs to generate whole business logic blocks, to understand code and to learn (sometimes good, sometimes poisoned learn).</p><p>But then, Claude Code appeared. Again, a non-expected success. And since that moment, software development has not been the same.</p><h3>From Prompt to Context</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2NB6bDKOjzLghJW_7fqGA.png" /></figure><p>In the ChatGPT era, the ones that have got into AI-assisted development, we were fighting to learn “how to create the perfect prompt”.</p><p>With every GPT, new prompt patterns arose, and we had to learn again and again how to interact with LLMs (negative prompting, initial context, rules, desired reply format, etc…).</p><p>But since Claude Code (and the following CLI-Agentic Tools), the perfect prompt was not only “not enough”, but not “the most important thing” anymore.</p><p>With CLI Agentic Tools, context is the Bible. And it is a truly smart and simple solution, which makes it unbelievably perfect. Simple markdown files, easy to read by humans and LLMs, no special format, widely accepted, as a memory system for the LLM, that needs no memory, but keeps every detail.</p><p>Since the moment tools like Claude Code appeared, with access to commands, to read terminal outputs, to read git history and with all that “unlimited context” that markdowns represent, software development changed forever.</p><p>Now, with a good structure of indexes, references and headers you can have all the documentation of your project.</p><p>From now, prompt is just the trigger of a bigger engineered structure of knowledge and tools.</p><p>With MCPs and Plugins you can interact with third-party services (like Sentry, Atlassian, RevenueCat, whatever!).</p><p>With Skills you can teach (or it teaches itself) how to do certain things, or how to face certain problems.</p><p>With agents, you can pre-warm the LLM to adopt a certain role with certain rules.</p><p>And with all of that combined, you can rule a whole team from your command line interface, able to consume, digest, and produce more content than your human mind can healthily process.</p><p>Onboardings have reduced from months to days. Team members’ styles can be replicated, problems? Quickly found and fixed!</p><p>And so, the need for developers, while still necessary, is now less aggressive than ever.</p><h3>What does it feel like to be an AI-Assisted Software Engineer?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxOjprcomGsfHa9gjinvXQ.png" /></figure><p>Do you remember a few years ago when we were talking about those one-of-a-kind 10x engineers? Those guys that were so valuable because they could carry insane amounts of complex work in record times?</p><p>Well, that’s now democratised.</p><p>As long as you paid attention to all of the above, as long as your project structure allows, and have a good context setup. You can just deliver at an insane speed.</p><p>And yeah, I felt that. I’m right now close to finishing a side project I’ve been working on for a little bit more than one month. This side project was fully made with AI assistance.</p><p>I defined the project and the technologies. I defined the design principles and owned the product decisions.</p><p>And even though I mostly supervised AI, it has done the code pretty much entirely, and so the design assets.</p><p>I’ve seen hundreds of lines of code created in front of me in seconds.</p><p>Entire features got from design to code within minutes.</p><p>The MVP was done in two days, but the rush was so, that in nearly two months, the WHOLE app is nearly finished, with every originally intended feature, with a consistent design, with pricing strategy, with ASO, with good-quality translations…</p><p>This is what not even a 10x engineer could have done, this is what took my sleep the same way ChatGPT did when it was released, and Claude Code did too.</p><p>This is the present and future of software creation, not just development.</p><h3>The missing opportunity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*814HCCb_6vl8f3gdUjVF2Q.png" /></figure><p>The tools are there, and at the point they are now, they are extremely less complex to use than people may think.</p><p>The real challenge? The weakest point of the chain.</p><p>These AI tools can understand programming styles and rules, architectures, patterns, frameworks, design systems, tasks, business context, and so on.</p><p>But humans are right now the weakest point on the chain. Humans introduced chaos.</p><p>It is worth nothing to have a completely automated software agentic team if your Design System Foundations are not written down nor accessible.</p><p>It is worth nothing that you have also that Design System perfectly accessible to LLMs if Product and Management doesn’t clearly provide definitions nor instructions.</p><p>It is worth nothing all of this if the human introduces chaos and holes into the system.</p><p>Because as a chain, everything stops when a part is missing or faulty.</p><h3>The solution we resist</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kii8Qg1bK2X5U6u81h1g6Q.png" /></figure><p>The solution is pretty simple actually. AI is to all of those profiles the same as it is to software engineers.</p><p>Designers can use Claude Code with Figma MCP or Pencil MCP to review, fix and document the Design System, and doing so write coherent Style Guides for AI Developers.</p><p>Product Owners can challenge their ideas with AI to look for gaps and better definitions before they move to deliver to the coding or design team.</p><p>Project Managers can co-define with AI like Claude Code or Claude Cowork what is needed in a JIRA ticket to be completely understood, even reviewing code.</p><p>And so every part of the chain…</p><h3>The inequality gap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3bFtWUdf-743vURQWdMgQ.png" /></figure><p>Now, there’s something that not many people are talking about, and it’s worth addressing.</p><p>When you discover the workflow with Claude Code, you start thinking “how could I have not seen this before?”, and you lock yourself into a 20USD/month plan in order to keep up, trading part of your salary for those productivity and resource benefits.</p><p>But it happens the same the day you try the Max plan. When you switch from 20 to 200USD, you get an insane amount of OPUS context of the best model, while before that you had to use Sonnet because every OPUS prompt consumes a ~5% of your session token limit, and hurts your weekly token availability.</p><p>There is a HUGE difference between PRO and MAX plans, but there is also a HUGE difference between Spain and US salaries.</p><p>And that difference doesn’t reflect in the product cost, MAX costs in Spain the same (or more due to taxes or direct conversion) than in the US, but salaries for software development are not even half of the US ones.</p><p>That creates a huge inequality, in which US or high-paid countries can rely on MAX plans more easily, while in low-paid countries, besides having the talent and the service availability, that spending means a much higher portion of the salary, creating an effective disadvantage if one wants to stay competitive.</p><p>This is not a complaint, it’s a reality. And it’s one that the industry should at least acknowledge, because talent is global, but purchasing power is not.</p><h3>The future ahead of us</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BHmSzDAeQ2O70aMh6aZD6g.png" /></figure><p>As I said, software creation will never be the same.</p><p>Early adopters are now AI-Boosted developers, and every time a new model gets out they see their work quality boosted for free.</p><p>AI is taking a piece of the cake in EVERY part of the process. From development to design and management, and believe me, those who reject the reality will be the ones that suffer the most, because offering resistance to an unstoppable force is not a smart choice.</p><p>More and more, sceptical developers are joining the new way of work, having to learn all of this that they rejected before in order to be competitive.</p><p>And I think this is good, honestly. We can use this as a chance to improve our communication skills, which is now the most important skill one can have.</p><p>We can save mental resources by delegating complex context and implementations to those never-tired agents, and we can keep that energy for ourselves and our families, the really most important thing.</p><p>I don’t really know how software creation will be like in five years from now. I don’t even know if I will have to start learning to be a carpenter or a farmer, because honestly, there are those people that say “software engineers will be obsolete in six months”, and those people that say “AI will never replace software engineers”, and having the chance to get hands-on with these technologies, I think none of them are right.</p><p>So, for now my way of facing this is to join the wave, to learn and enjoy the new way of software creation and use it to boost up my productivity, inside and outside my work, but who knows how will this world be in two years, my mind can no longer predict how things will change in this field, as it is faster than I have ever imagined, and the more it changes, the faster it does.</p><p>Having said all of this, my final conclusion would be:</p><p>Don’t be an observer, don’t resist the unstoppable force. Join, experiment, use it to your benefit, learn and try to get more quality of life with it.</p><p>Adaptability is one of the most valuable skills, and if you are able to learn, adapt and enjoy, you will survive.</p><p>The future is terrifying and brilliant at the same time, and I think that’s exactly what makes it worth being part of. Because the best moment to shape what comes next is right now, while we still can.</p><p>I won’t lie, this future has me scared. But it also brought back to me the feeling of discovering programming for the first time. It now more than ever before feels like a superpower and a great responsibility, and now more than ever before is the best moment to create, to enjoy, and, something that comes deeply tight to our profession, never stop learning.</p><p>Happy coding to you all!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90777ede9e2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use ‘RemoteResult’ to claim back your data state control]]></title>
            <link>https://medium.com/@juancolilla_66813/use-remoteresult-to-claim-back-your-data-state-control-6d326663838c?source=rss-ee11ac4cf3ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d326663838c</guid>
            <category><![CDATA[cats]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Juan Colilla]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 17:36:21 GMT</pubDate>
            <atom:updated>2024-02-18T02:00:48.288Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern app development, especially those built on reactive and declarative designs like SwiftUI, effective state management has become a critical component. This is because the application state, at its core, dictates what the user sees on the screen at any given moment.</p><p>Mishandling state can lead to inconsistent user interfaces, hard-to-trace errors, and a degraded user experience. Therefore, understanding and applying effective strategies to control and react to changes in data state — from initial loading to update and error handling — is essential for creating robust, maintainable, and user-friendly applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Zk_iETiTZt2MLKR1tUHtg.jpeg" /></figure><p>Most of the applications we build require data located on a server, which will deliver it to us at varying speeds, requiring visual feedback to our users.</p><p>SwiftUI, with its innate reactivity, has made things “simpler” for us, but we still need to manage our data state to know what to display on the screen and when. In today’s article, I’ll try to introduce my proposal, based on the ‘Result’ type, extending its functionality for full control of the data flow, which is highly convenient for declarative interfaces and reactive programming.</p><p>My proposal is primarily based on the use of an enum called ‘RemoteResult.’ This enum, like Result, will have two familiar cases indicating ‘success’ and ‘failure,’ with their respective associated types, typically ‘Success’ and ‘Failure: Error.’</p><pre>enum Result&lt;Success, Failure: Error&gt; {<br> case success(Success)<br> case failure(Failure)<br>}</pre><p>To build ‘RemoteResult’, we first need to understand ‘what we want’. We want a versatile way to mark the states of a resource to react to its changes from our views. To do this, starting from the success and failure cases of Result, which already adequately represent these events in an attempt to download resources, we could add two new states that might interest us, such as ‘idle’ and ‘loading’.</p><p>With ‘idle’, we have a base value from which to initialize resources from within the logic itself, without the need to establish optionals or extra code that clutters development. The concept is simple: if a resource is ‘idle,’ its download has not yet started, remaining in the default state.</p><p>With ‘loading’, we have a way to indicate to our views that the download of a resource is in progress. It is a state that does not contain associated data, as there is none yet, but it already allows us to know with certainty that the download process has started, making it easier for us to show the user, for example, a loading spinner. Especially in SwiftUI.</p><p>With these two additions, the first version of ‘RemoteResult’ would look like this:</p><pre>enum RemoteResult&lt;Success, Failure: Error&gt; {<br>    case idle<br>    case loading<br>    case success(Success)<br>    case failure(Failure)<br>}</pre><p>This is starting to take shape; with just 6 lines of code, we already have a very versatile type to work with. Now, let’s see how it would be used in a SwiftUI view. The first step is to create the types that would fit within the ‘Success’ and ‘Failure’ generics. Let’s consider the following examples.</p><p>Success:</p><pre>struct User {<br>    let name: String<br>    let mail: String<br>}</pre><p>Failure:</p><pre>enum APIError: Error {<br>case clientError<br>case serverError<br>}</pre><p>Alright then, with data to replace the generics, in our SwiftUI view, we would just need to include the following:</p><pre>@State<br> var userData: RemoteResult&lt;User, APIError&gt; = .idle</pre><p><strong>Disclaimer:</strong> For educational purposes, this article will use a simple MV architecture to facilitate understanding, but its content is applicable to other architectures such as MVVM and TCA. Additionally, the responsibility management and logic are certainly improvable.</p><p>Let’s continue. We now have the types we’re going to use in our application and the variable that will store both the data when it exists and its state at all times. Since it’s marked with ‘@State’, its changes will be monitored by SwiftUI, ensuring the view is updated when there is a relevant change affecting it.</p><p>With this in mind, a very simple view that perfectly exemplifies the use of ‘RemoteResult’ (thanks to ResultBuilders) is as follows:</p><pre>struct ContentView: View {<br>    <br>    @State<br>    var userData: RemoteResult&lt;User, APIError&gt; = .idle<br>    <br>    var body: some View {<br>        VStack {<br>            switch userData {<br>            case .idle:<br>                EmptyView()<br>            case .loading:<br>                ProgressView()<br>                    .progressViewStyle(.circular)<br>            case .success(let user):<br>                Text(&quot;Hello \(user.name)&quot;)<br>            case .failure(_):<br>                ContentUnavailableView(&quot;No User was found&quot;, systemImage: &quot;person.fill&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>As you can see, the constructor of this view has no external dependencies. User data is in a latent state, waiting for something to trigger a state change, but there are no optional variables, and the SwiftUI view has been instructed to know at all times what to display based on the state of the associated data.</p><p>Let’s see how we could make real use of this view. We should start by creating a function that allows us to retrieve data from a remote source, for example, something like this:</p><pre>private func getUserData() async {<br> self.userData = .loading<br>        let request = URLRequest(url: URL(string: &quot;API_URL&quot;)!)<br>        do {<br>            let (data, _) = try await URLSession.shared.data(for: request)<br>            let userData = try JSONDecoder().decode(User.self, from: data)<br>            self.userData = .success(userData)<br>        } catch {<br>            self.userData = .failure(error) // Error management simplified.<br>        }<br>    }</pre><p>Once we have the function that will retrieve the data, all we have to do is call it, and SwiftUI provides us with a very convenient method that allows us to automate data fetching from the first appearance of the screen.</p><p>We just need to add this at the end of our VStack:</p><pre>.task {<br>    await getUserData()<br> }</pre><p>With this, we would have practically all the logic in place, and ‘RemoteResult’ would be fulfilling its most basic function, which is to automatically control the states and make the view reactive to changes in the associated data. When the view is instantiated, the data is in the ‘idle’ state, and then it is set to ‘loading’ thanks to the ‘onAppear’ method triggering the ‘getUserData’ function.</p><p>The change in the data state from ‘idle’ to ‘loading’ will cause SwiftUI to recalculate the view, and instead of an ‘EmptyView’, it will display a loading indicator, ‘ProgressView’. The ‘getUserData’ function has two possible outcomes: either the resource download succeeds, in which case our ‘RemoteResult’ will become ‘success(userData)’, or the download fails for any reason, in which case it will become ‘failure(error)’. In both cases, our data flow will have gone through all possible paths and left us with the necessary information to react to and/or communicate the data state to the user at all times.</p><p>To this part, this article is based on learnings from Bobby Bobak <a href="https://bobby.build/2023/swift-remote-result-type.html">post at Bobby’s blog</a>.</p><p><strong>Use it with The Composable Architecture</strong></p><p>Alright, we’ve seen how to build a <strong>RemoteResult</strong> and how we can use it, but hardly anyone programs like this in production; generally, we are forced to use architectures or programming patterns that decouple the view from the logic. However, RemoteResult is still incredibly useful!</p><p>Let me give you an example from my personal experience; I use <strong>TCA</strong> (<a href="https://github.com/pointfreeco/swift-composable-architecture">The Composable Architecture</a> by <a href="https://www.pointfree.co/">PointFree</a>) and use UseCases in my daily work. So, the question we might ask now is, how can we adapt RemoteResult for a scenario like this?</p><p>Well, let’s start by revisiting the enum. In order to use RemoteResult in an application built with TCA, the control of RemoteResult should be moved to the State of the Reducer associated with the view so that it is controlled there, and the state change that triggers the view update is managed from there.</p><p>To do this, we need to make a simple change: TCA works by ‘diffing’ the State whenever any change is observed from the associated view’s ViewStore. For this to work, our State must comply with <strong>Equatable</strong>, and one of the changes we need to make to RemoteResult is precisely that, making it Equatable.</p><p>For RemoteResult to be Equatable, be careful, we need to make its associated types for Success and Failure Equatable as well!</p><p>So, it would look something like this:</p><pre>enum RemoteResult&lt;Success: Equatable, Failure: Equatable &amp; Error&gt; : Equatable {<br>    case idle<br>    case loading<br>    case success(Success)<br>    case failure(Failure)<br>}</pre><p>With this simple modification, RemoteResult is now compatible with the state comparison logic of TCA, with no major modifications required. This allows us to link loading views and other advantages to changes in this state housed in the State of our Reducer.</p><p>One less problem to worry about! Now let’s address the UseCases. In my case, UseCases are structs containing a single method called “execute”, which usually returns a type of “Result&lt;Something, APIError&gt;” to manage what to do in case the UseCase succeeds or fails from the Reducer.</p><p>It doesn’t make sense for me to use RemoteResult in a UseCase since it’s an operation that will never be in an idle state. I never keep the instance of a UseCase; I instantiate and execute it on the same line and usually as an asynchronous task thanks to the use of async/await. With this in mind, knowing that the “idle” and “loading” cases are exclusively for view management, it’s very convenient for our RemoteResult to have a way to absorb the return value of our UseCase once we receive it.</p><p>Fortunately, since RemoteResult is based on Result, it allows us to make a simple modification in the initializer for this purpose:</p><pre>enum RemoteResult&lt;Success: Equatable, Failure: Equatable &amp; Error&gt;: Equatable {<br>    case idle<br>    case loading<br>    case success(Success)<br>    case failure(Failure)<br>    <br>    init(_ result: Result&lt;Success, Failure&gt;) {<br>        switch result {<br>        case .success(let data):<br>            self = .success(data)<br>        case .failure(let error):<br>            self = .failure(error)<br>        }<br>    }<br>}</pre><p>And just like that, with these two small modifications, we can manage the logic from our Reducer (or ViewModel) and not lose the functionality that RemoteResult brings to view management.</p><p>As shown in the following examples:</p><pre>struct LoginUseCase {<br>    func execute(loginInfo: LoginEncoder) async -&gt; Result&lt;LoginDecoded, APIError&gt; {<br>        do {<br>            let authData: LoginDecoded = try await Environment.apiClient.send(<br>                LoginRequest(<br>                    body: [<br>                        &quot;user&quot;: loginInfo.user,<br>                        &quot;password&quot;: loginInfo.password<br>                    ]<br>                ),<br>                authorized: false<br>            )<br>            return .success(authData)<br>        } catch let error as APIError {<br>            return .failure(error)<br>        } catch {<br>            console(error)<br>            return .failure(.UNDERLYING_ERROR(error))<br>        }<br>    }<br>}</pre><p>In the example above, a UseCase is shown that asynchronously authenticates a user, which could be executed as follows from a Reducer in TCA:</p><pre>import ComposableArchitecture<br><br>struct LoginReducer: Reducer {<br>    struct State: Equatable {<br>        var loginData: RemoteResult&lt;LoginDecoded, APIError&gt; = .idle<br>    }<br>    <br>    enum Action: Equatable {<br>        case loginPressed<br>        case _loginExecuted(Result&lt;LoginDecoded, APIError&gt;)<br>    }<br>    <br>    var body: some ReducerOf&lt;Self&gt; {<br>        Reduce { state, action in<br>       case .loginButtonPressed:<br>       state.loginData = .loading<br>       let loginInfo: LoginEncoder = .init(<br>           user: state.user,<br>           password: state.password,<br>        ) <br>        return .run { send in<br>           let authData: Result&lt;LoginDecoded, APIError&gt; = await LoginUseCase().execute(loginInfo: loginInfo)<br>           await send(._loginExecuted(loginData))<br>        }<br>            <br>        case ._loginExecuted(let loginResponse):<br>            switch loginResponse {<br>            case .success(let loginData):<br>                // Manage your auth data<br>            case .failure(let error):<br>                // React to any error during the call<br>            }<br>        }<br>    }<br>}</pre><p>And if you wanted to use it in a ViewModel, it would be something like this:</p><pre>import Combine  <br><br>class LoginViewModel: ObservableObject {<br>    <br>    @Published <br>    var loginData: RemoteResult&lt;LoginDecoded, APIError&gt; = .idle<br>    <br>    func login() async -&gt; Result&lt;LoginDecoded, APIError&gt; {<br>        loginData = .loading<br>        let loginInfo: LoginEncoder = .init(<br>            user: state.user,<br>            password: state.password,<br>        ) <br>        let authData: Result&lt;LoginDecoded, APIError&gt; = await LoginUseCase().execute(loginInfo: loginInfo)<br>        return authData   <br>    }<br>}</pre><p>With these two examples, I conclude the article on how and why RemoteResult is a good way to control data flow with SwiftUI and reactive programming. I hope it has helped you learn something or provided a new perspective.</p><p><strong>There’s always room for improvements…</strong></p><p>After its publication, the article has sparked various doubts and opinions that have led to learning and potential improvements, as well as interesting debates about the content. My intentions in writing it were diverse, but the main one was learning, both for myself and for those who read it.</p><p>Allow me to expand the article starting with a small adjustment suggested by <a href="http://diariodeprogramacion.com/">Julian Alonso</a>, Tymit’s iOS Tech Lead.</p><p><strong>Contemplate instead of require</strong></p><p>One of the adjustments mentioned in the article is to comply with Equatable to facilitate the integration of the enum with RemoteResult. Specifically, this signature:</p><pre>enum RemoteResult&lt;Success: Equatable, Failure: Equatable &amp; Error&gt;: Equatable</pre><p>As Julian rightly points out, by establishing the main signature in this way, we are requiring that RemoteResult (and all elements within Success and Failure) conform to Equatable, something that may not always be necessary or desired and that can sometimes force us to make our models Equatable, which, with very complex models, can be a headache.</p><p>This can be modified so that this requirement becomes a consideration, which would allow using RemoteResult with models and errors that are not Equatable, as well as considering cases where they are, so that compatibility with TCA, for example, is not lost.</p><p>The resulting code would be this:</p><pre>enum RemoteResult&lt;Success, Failure: Error&gt; {<br>    case idle<br>    case loading<br>    case success(Success)<br>    case failure(Failure)<br>    <br>    init(_ result: Result&lt;Success, Failure&gt;) {<br>        switch result {<br>        case .success(let data):<br>            self = .success(data)<br>        case .failure(let error):<br>            self = .failure(error)<br>        }<br>    }<br>}<br><br>extension RemoteResult: Equatable where Success: Equatable, Failure: Equatable {}</pre><p>With this code, as long as Success and Failure are Equatable, RemoteResult will also be, but it’s not mandatory. And thanks to Success and Failure being Equatables, Swift automatically synthesizes the static ‘==’ function, saving you from writing that code full of ‘rhs’, ‘lhs’…</p><p><strong>What utility does ‘idle’ have?</strong></p><p><a href="https://michaellong.medium.com/">Michael Long</a> has suggested an interesting debate in the comments, for which I am grateful. Michael argues that the ‘idle’ case is completely unnecessary since it can be replaced by making the state variable optional, so ‘case .idle’ would be represented with ‘nil’.</p><p>The first thing I want to say about this is that it’s true. That specific case is perfectly replaceable by managing an optional state variable without losing any functionality, but that doesn’t mean the approach is better (or worse).</p><p>My opinion on this matter is that it’s more related to each person’s programming style. That is, the comparison between enum cases as well as checking whether a variable has a value or not (which underneath is itself a comparison between enum cases) are two highly optimized operations in Swift (from what I’ve been able to research), so there’s no technical reason that gives an advantage to one option over the other.</p><p>That being said, I still believe that the ‘case .idle’ is the best alternative, and I’ll explain why; if we make ‘RemoteResult’ dispense with ‘idle’ and make it optional in the state, it would look like this:</p><pre>struct ContentView: View {<br>    <br>    @State<br>    var userData: RemoteResult&lt;User, CustomError&gt;?<br>    <br>    var body: some View {<br>        VStack {<br>            if let userData {<br>                switch userData {<br>                case .loading:<br>                    ProgressView()<br>                        .progressViewStyle(.circular)<br>                case .success(let user):<br>                    Text(&quot;Hello \(user.name)&quot;)<br>                case .failure(_):<br>                    ContentUnavailableView(&quot;No User was found&quot;, systemImage: &quot;person.fill&quot;)<br>                }<br>            } else {<br>                EmptyView()<br>            }<br>        }<br>        .task {<br>            await getUserData()<br>        }<br>    }<br>}</pre><p>Let’s compare it with the original code:</p><pre>struct ContentView: View {<br>    <br>    @State<br>    var userData: RemoteResult&lt;User, CustomError&gt; = .idle<br>    <br>    var body: some View {<br>        VStack {<br>            switch userData {<br>            case .idle:<br>                EmptyView()<br>            case .loading:<br>                ProgressView()<br>                    .progressViewStyle(.circular)<br>            case .success(let user):<br>                Text(&quot;Hello \(user.name)&quot;)<br>            case .failure(_):<br>                ContentUnavailableView(&quot;No User was found&quot;, systemImage: &quot;person.fill&quot;)<br>            }<br>        }<br>        .task {<br>            await getUserData()<br>        }<br>    }<br>}</pre><p>The way I see it, the code is practically the same, but when using an optional, we are forced to unwrap its value to ensure that we can use it.</p><p>Another option that would reduce the code using optional would look like this:</p><pre>struct ContentView: View {<br>    <br>    @State<br>    var userData: RemoteResult&lt;User, CustomError&gt;?<br>    <br>    var body: some View {<br>        VStack {<br>            switch userData {<br>            case .loading:<br>                ProgressView()<br>                    .progressViewStyle(.circular)<br>            case .success(let user):<br>                Text(&quot;Hello \(user.name)&quot;)<br>            case .failure(_):<br>                ContentUnavailableView(&quot;No User was found&quot;, systemImage: &quot;person.fill&quot;)<br>            default:<br>                EmptyView()<br>            }<br>        }<br>        .task {<br>            await getUserData()<br>        }<br>    }<br>}</pre><p>But in this case, we would be setting a ‘default’, which would strike back to us the day we wanted to extend the number of states that ‘RemoteResult’ contains, since the compiler wouldn’t force us to consider them all.</p><p>Another curiosity lies in the very essence of optionals in Swift, because an optional is a wrapper over a type that encapsulates it in an enum. Optionals in Swift are built like this:</p><pre>enum Optional&lt;WrappedType&gt; : ExpressibleByNilLiteral {<br><br>    case none<br>    case some(WrappedType)<br><br>    public init(_ some: WrappedType)<br>}</pre><p>Why is this interesting? Because following Michael Long’s proposal, by making ‘RemoteResult&lt;Success, Failure&gt;’ optional, we would be establishing a state variable that would actually look like this:</p><pre>enum Optional&lt;RemoteResult&lt;Success, Failure&gt;&gt; : ExpressibleByNilLiteral {<br><br>    case none<br>    case some(RemoteResult&lt;Success, Failure&gt;)<br><br>    public init(_ some: RemoteResult&lt;Success, Failure&gt;)<br>}</pre><p>And this code gives rise to curiosities like the following when doing a switch on ‘userData’, and that switch in code could perfectly look like this:</p><pre> switch userData {<br>   case .loading:<br>   case .success(let user):<br>   case .failure(let error):<br>   case .none:<br>   case .some(let remoteResult):<br>     switch remoteResult {<br>       case .loading:<br>       case .success(let user):<br>       case .failure(let error)<br>      }<br>  }</pre><p>In the switch statement, the return contents of the cases have been removed to better illustrate the number of possibilities it encompasses, as well as how confusing it can become.</p><p>If we fill that switch with view returns, we could have inconsistencies or duplicate cases, which would be perfectly evaluable and would result in code that is difficult to understand due to its apparent lack of logic (although functionally, the ‘case some’ would never be entered since there is no ‘fallthrough’ to allow execution to continue after finding a match). Thankfully, no one would use a switch in this way, but it’s interesting to see that this possibility exists.</p><p>Ultimately, while there may not be an apparent use case for ‘.idle’ that justifies its existence over using optionality, the reality is that its presence makes the code much more structured and readable. It also facilitates following safe programming practices since the state will always be in a known value, understood in one of the 4 possibilities that ‘RemoteResult’ contemplates.</p><p>Feel free to use the comments section to ask questions, suggest improvements, point out errors, and anything else you’d like! If you use other methods of controlling data flow that you believe are better (more optimal, readable, simpler, and/or more effective), I’ll be happy to read your proposals!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d326663838c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>