<?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[PUKAKI MAGAZINE - Medium]]></title>
        <description><![CDATA[https://pukakilab.com/ - Medium]]></description>
        <link>https://medium.com/pukaki-lab?source=rss----e05dc67acde4---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>PUKAKI MAGAZINE - Medium</title>
            <link>https://medium.com/pukaki-lab?source=rss----e05dc67acde4---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:57:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/pukaki-lab" 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 Waiting Shouldn’t Cost a Thread]]></title>
            <link>https://medium.com/pukaki-lab/why-waiting-shouldnt-cost-a-thread-83f11f5cd20f?source=rss----e05dc67acde4---4</link>
            <guid isPermaLink="false">https://medium.com/p/83f11f5cd20f</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Basin]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 13:44:02 GMT</pubDate>
            <atom:updated>2026-10-19T15:35:07.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*_9KrX8iMog1XFoQhhR2sgA.png" /></figure><h3>Every Scroll Spawned Sixty Threads</h3><h3>Prologue: The View That Looked Fine</h3><p>The thumbnails in a list screen were loaded by a view that looked like this. SwiftUI’s AsyncImage has no cache, so we had written our own.</p><pre>struct CachedAsyncImage&lt;Content: View, Placeholder: View&gt;: View {<br>    let url: URL?<br>    let content: (Image) -&gt; Content<br>    let placeholder: () -&gt; Placeholder<br><br>    @State private var uiImage: UIImage?<br><br>    var body: some View {<br>        Group {<br>            if let uiImage { content(Image(uiImage: uiImage)) }<br>            else { placeholder() }<br>        }<br>        .onAppear(perform: load)<br>    }<br><br>    private func load() {<br>        guard let url else { return }<br>        if let cached = ImageMemoryCache.shared.image(for: url) {<br>            uiImage = cached<br>            return<br>        }<br>        DispatchQueue.global().async {<br>            guard let data = try? Data(contentsOf: url),<br>                  let image = UIImage(data: data) else { return }<br>            ImageMemoryCache.shared.set(image, for: url)<br>            DispatchQueue.main.async {<br>                uiImage = image<br>            }<br>        }<br>    }<br>}</pre><p>When the view appears, it checks the cache. On a miss, it fetches on a global queue, decodes, and assigns the result to @State on main. Simple, and easy to read.</p><p>This isn’t a contrived bad example. “AsyncImage has no cache → I&#39;ll write one → Data(contentsOf:) is a one-liner&quot; is a path many of us have walked.</p><p>The symptoms show up under fast scrolling. The scroll stutters, memory climbs, and when the list refreshes while requests are still in flight, images land in rows they don’t belong to. Pause the app in Xcode mid-scroll and the thread list runs past seventy.</p><p>To put numbers on it, I rebuilt this view in a reproduction project: a 200-row list of thumbnails behind a local server that answers in 250 ms, flicked from top to bottom and back by code so every run is the same. Every number in this piece comes from that project, measured in the iOS Simulator on an M1 Pro. They are relative numbers, not device numbers — but the shape of the problem doesn’t change.</p><p>For a long time this code didn’t look like a problem. With a short list and small images, nothing happens. It surfaced when the list grew to a few hundred items and users started flicking through them.</p><h3>1. What This Code Is Actually Doing</h3><h4>1.1 Two Kinds of Work</h4><p>Everything an app does falls into roughly two kinds.</p><ul><li><strong>Work the CPU does itself</strong>: image decoding, JSON parsing, encryption, arithmetic.</li><li><strong>Work the CPU hands off and waits for</strong>: network, disk, a Bluetooth reply, a timer, another process.</li></ul><p>load() mixes the two. Data(contentsOf:) is <em>waiting</em> for the network. Decoding the image is work the CPU <em>does</em>.</p><p>The trouble is in the first half. Data(contentsOf:) is synchronous. It doesn&#39;t return until the response arrives, and for that whole stretch the thread stands there doing nothing — but still <strong>occupied</strong>. Sixty rows pass through the screen, onAppear fires sixty times, and sixty threads stand around, each waiting for its own response.</p><pre>row 1 appears    → thread 1 blocks in Data(contentsOf:)<br>row 2 appears    → thread 2 blocks<br>...<br>row 60 appears   → thread 60 blocks<br><br>sixty threads, zero work</pre><p>That’s where the question came from.</p><blockquote><strong>If we’re only waiting, why does it need a thread at all?</strong></blockquote><p>Holding one thread is nothing. The problem is what happens when they pile up.</p><h4><strong>1.2 Why Sixty Is Different From One</strong></h4><ul><li>Every thread reserves a 512 KB stack plus kernel bookkeeping. Sixty idle threads reserve about 30 MB of address space, most of it never touched — a few megabytes resident. That alone isn’t the memory problem; the real one comes later.</li><li>GCD doesn’t create threads forever. Somewhere around 64 it stops, and new work can’t even start — it waits in the queue. That was why images kept arriving long after scrolling had stopped: 9.7 seconds after, in the reproduction.</li><li>The stutter came from the same place, one step removed. When SwiftUI draws an image, it decodes it on a GCD global queue and waits for the result inside the Core Animation commit. With all 64 GCD threads parked in Data(contentsOf:), that decode couldn&#39;t start, so the main thread sat in dispatch_group_wait until a download finished and gave a thread back. In the reproduction that was 80% of the main thread&#39;s time while scrolling back up, in stalls of one to two seconds. The thread explosion didn&#39;t just waste threads; it starved the framework&#39;s own work.</li><li>One step further is deadlock. If a sleeping thread is waiting for a signal that has to come from another GCD thread, and every thread is asleep, there’s no one left to send it. This code didn’t go that far — the kernel’s network stack does the waking — but put a semaphore into the same shape and it will.</li></ul><p>There’s one more thing hiding in this code, and it only surfaced later. UIImage(data:) doesn&#39;t decode the image. It reads the header and defers the real decode to the first time the image is drawn — at commit time, with the main thread waiting on it. So the &quot;background decoding&quot; the global queue was supposedly doing wasn&#39;t happening there at all. It was happening at draw time, on the same starved pool, with the main thread blocked behind it.</p><h4>1.3 The Wrong-Row Image Is a Different Bug</h4><p>The image landing in the wrong row is a separate problem. onAppear has no matching cancellation. When a row&#39;s url changes while a request is in flight — a refresh that swaps thumbnails, a row that is handed a new item — the request made for the previous url keeps running, comes back, and overwrites uiImage. GCD has no structure for cancelling work once it has been dispatched. In the reproduction, with the list refreshing every 400 ms during a scroll, 186 of 393 completed images (47%) landed in a row whose url had already moved on.</p><h3>2. Why GCD Led Us Here</h3><p>Whoever wrote this code didn’t make a mistake. Under GCD, this was the natural choice.</p><h4>2.1 A Closure Can’t Pause</h4><p>GCD’s unit of work is a closure. A closure runs from start to finish, and <strong>there is no way to stop in the middle of a function and pick up later.</strong> If you want “check cache → fetch → decode → store → display” to read as one flow, you have two options.</p><p><strong>Callbacks</strong> — the thread stays free, but the code splits.</p><pre>URLSession.shared.dataTask(with: url) { data, _, _ in<br>    guard let data else { return }<br>    DispatchQueue.global().async {<br>        guard let image = UIImage(data: data) else { return }<br>        ImageMemoryCache.shared.set(image, for: url)<br>        DispatchQueue.main.async {<br>            uiImage = image<br>        }<br>    }<br>}.resume()</pre><p>Receiving, decoding, and displaying end up three layers deep. Add error handling and cancellation and it goes deeper still.</p><p><strong>Synchronous calls</strong> — the code reads in order, but the thread is held.</p><pre>DispatchQueue.global().async {<br>    let data = try? Data(contentsOf: url)     // the thread stops here<br>    let image = UIImage(data: data)<br>    DispatchQueue.main.async { ... }<br>}</pre><p>Given the choice, the second one is easier. And GCD lets you get away with it: it quietly spins up one more thread and moves on. For a single row, it works perfectly. That is exactly why the pattern spreads through a codebase without a single warning.</p><h4>2.2 It Was Already Everywhere</h4><p>Search a mature codebase for Data(contentsOf:) next to DispatchQueue.global().async and you rarely find just one. Each one is harmless on its own. Until a few dozen of them run at once on the same screen.</p><h3>3. What Swift Concurrency Actually Changed</h3><p>Swift Concurrency changed exactly one thing. <strong>A function can now stop in the middle and resume later.</strong></p><pre>func loadImage(from url: URL) async throws -&gt; UIImage? {<br>    let (data, _) = try await URLSession.shared.data(from: url)   // the function folds here<br>    return await UIImage(data: data)?.byPreparingForDisplay()     // and resumes here when the response arrives<br>}</pre><p>At each await, the compiler cuts the function into two pieces. When the first piece finishes, the thread is handed back and the local variables are kept on the heap. When the response comes in, whichever thread is free picks up the second piece. The code reads like the synchronous version; the behavior is the callback version&#39;s. Nothing is held while waiting.</p><h4>3.1 The Cooperative Pool, in Three Terms</h4><p>Once waiting stops holding threads, you don’t need many of them. So Swift Concurrency keeps <strong>exactly as many threads as there are cores.</strong> That’s the cooperative thread pool. Three terms are enough to read the experiments below.</p><ul><li><strong>Job</strong>: a slice of execution between two awaits. The thing that actually runs on a thread.</li><li><strong>Executor</strong>: the queue jobs wait in. One global, plus one per actor instance.</li><li><strong>Pool thread</strong>: fixed at the core count. Pulls a job from the queue, runs it, and the moment that job hits await, drops it and picks up the next.</li></ul><h4>3.2 The One Rule</h4><p>One rule comes attached. <strong>Never block a pool thread.</strong> With six threads, blocking one on Data(contentsOf:) throws away a sixth of your throughput. Block all six and the entire async world stops.</p><p>This rule is why swapping DispatchQueue.global().async for Task { } in the prologue&#39;s code, and changing nothing else, is <strong>more dangerous than it was under GCD.</strong> GCD&#39;s ceiling was 64. The pool&#39;s is the core count — eight on the Mac these experiments ran on, six on a recent iPhone. Six rows scroll past and not just image loading but every piece of async code in the app freezes. The cliff moved much closer.</p><p>The deeper mechanics are in WWDC21’s <a href="https://developer.apple.com/videos/play/wwdc2021/10254/">Swift concurrency: Behind the scenes</a>.</p><h3>4. Does It Hold Up? Three Experiments</h3><p>I understood it on paper. I wanted to see the numbers. Three experiments, built with -O and run on an M1 Pro (8 cores: 6 performance, 2 efficiency). Each time is the median of seven runs.</p><h4>4.1 CPU-bound: Summing a Large Array</h4><p>Summing fifty million Doubles — serially, with DispatchQueue.concurrentPerform, and with withTaskGroup.</p><pre>Method                        Time      Speedup<br>----------------------------  --------  ------------------<br>Serial for                    47.2 ms   1×<br>concurrentPerform, 10 chunks  10.0 ms   4.7×<br>TaskGroup, 10 chunks          10.0 ms   4.7×<br>TaskGroup, 100 chunks         7.8 ms    6.0×<br>TaskGroup, 1,000 chunks       8.1 ms    5.8×<br>TaskGroup, 100,000 chunks     103.6 ms  slower than serial</pre><p>Eight cores, six of them performance cores, and the best split lands at 6.0× — about what the hardware allows. Ten equal chunks on eight unequal cores lose a little to the tail; a hundred chunks balance better. Between GCD and Swift there is no difference at all. <strong>For CPU work, the tool is not the answer.</strong> The core count is the ceiling, and no tool lifts it.</p><p>Task creation does have a cost, but it shows up far later than I expected. At 10,000 chunks the TaskGroup starts losing ground, and at 100,000 it is slower than the serial loop — while concurrentPerform, which doesn&#39;t allocate a task per iteration, still finishes in 15 ms. Whichever way we write the decoding step, it costs the same.</p><h4>4.2 I/O-bound: N Things Waiting</h4><p>N tasks each waiting 200 ms, launched together. Measured the threads actually used and the total time. A scaled-down version of N rows requesting images at once. GCD waits with a synchronous call; Swift waits with await.</p><pre>// GCD + synchronous wait (same shape as the prologue)<br>DispatchQueue.global().async(group: group) {<br>    Thread.sleep(forTimeInterval: 0.2)     // stands in for Data(contentsOf:)<br>    record(pthread_self())<br>}<br><br>// Swift Concurrency<br>group.addTask {<br>    try? await Task.sleep(for: .milliseconds(200))<br>    return &quot;\(pthread_self())&quot;<br>}</pre><pre>N                                GCD threads  GCD time  Swift threads  Swift time<br>-------------------------------  -----------  --------  -------------  ----------<br>10                               10           210 ms    9              207 ms<br>64                               64           210 ms    6              208 ms<br>100                              64           419 ms    5              202 ms<br>1000                             64           3317 ms   9              212 ms<br>1000, pool forced to one thread  —            —         1              211 ms</pre><p>GCD grows threads with the number of waiters, hits the ceiling at 64, and from there splits the work into two rounds, then sixteen. Swift never goes past the core count — five to nine threads here, and those are busy running the tiny first halves of a thousand tasks, not waiting. The time doesn’t move. It let go of the thread while it waited.</p><p><strong>The difference lives entirely in the waiting, not in the work.</strong> And the prologue’s Data(contentsOf:) is precisely that waiting.</p><p>There is a tool for catching code that blocks the pool. Set LIBDISPATCH_COOPERATIVE_POOL_STRICT=1 in the scheme&#39;s environment and the pool shrinks to a single thread, so one blocking call anywhere stops everything on the spot. It also makes the point more bluntly than any table — that last row is it. With the pool forced down to one thread, a thousand concurrent 200 ms waits still finished in 211 ms. One thread. Waiting needs no thread at all.</p><h4>4.3 When the Two Are Mixed</h4><p>Eight CPU jobs of three seconds each — decoding, say — one per core, are running when a network response comes in. How late is the response handled?</p><pre>Condition                                       Response delay<br>----------------------------------------------  --------------<br>CPU jobs and the response at the same priority  2950 ms<br>Response one priority level above the CPU jobs  2–17 ms<br>CPU jobs call Task.yield() every ~5 ms          ~10 ms<br>CPU jobs call Task.yield() every ~50 ms         ~50 ms</pre><p>At equal priority, the pool is one line. The job that handles the response sits in the queue until a decode finishes, and the screen that was awaiting a result wakes up three seconds late. The app doesn&#39;t die; it just goes quiet.</p><p>Give the response a higher priority than the decodes — .userInitiated over .medium, or .medium over .utility; only the relative order matters — and the runtime hands it a thread of its own. The eight decodes kept running on their eight threads, and the response resumed on a ninth, in single-digit milliseconds. The cooperative pool is sized per priority level, not once for the whole app.</p><p>The other route is to make the heavy work yield. With Task.yield() every 5 ms the response gets in within 10 ms; every 50 ms, within 50. The delay is whatever interval you choose.</p><p>The cooperative pool doesn’t reduce the total amount of CPU work. Keeping light work from getting stuck behind heavy work is still the developer’s job — by priority, or by yielding.</p><h3>5. The Fix</h3><p>Two things needed fixing: waiting that held a thread, and the previous request surviving row reuse. Three options were on the table.</p><pre>Approach                                                                  When                                         Trade-off<br>------------------------------------------------------------------------  -------------------------------------------  -------------------------------------------------------------------<br>URLSession.data(from:) + SwiftUI .task(id:)                               the network API offers async                 Cleanest. Cancellation is tied structurally to the view&#39;s lifecycle<br>Wrap a callback API in withCheckedContinuation                            an SDK or legacy API offers only callbacks   Cancellation needs separate handling<br>Isolate on a GCD queue outside the pool, then bridge with a continuation  a synchronous blocking API can&#39;t be changed  A GCD thread absorbs the blocking. Many calls, many threads</pre><p>URLSession had an async API and the deployment target was iOS 16. The first option.</p><pre>// Before<br>struct CachedAsyncImage&lt;Content: View, Placeholder: View&gt;: View {<br>    let url: URL?<br>    let content: (Image) -&gt; Content<br>    let placeholder: () -&gt; Placeholder<br><br>    @State private var uiImage: UIImage?<br><br>    var body: some View {<br>        Group {<br>            if let uiImage { content(Image(uiImage: uiImage)) }<br>            else { placeholder() }<br>        }<br>        .onAppear(perform: load)          // no cancellation<br>    }<br><br>    private func load() {<br>        guard let url else { return }<br>        if let cached = ImageMemoryCache.shared.image(for: url) {<br>            uiImage = cached<br>            return<br>        }<br>        DispatchQueue.global().async {<br>            guard let data = try? Data(contentsOf: url),   // thread held while waiting<br>                  let image = UIImage(data: data) else { return }<br>            ImageMemoryCache.shared.set(image, for: url)<br>            DispatchQueue.main.async {<br>                uiImage = image                            // lands in the wrong row after reuse<br>            }<br>        }<br>    }<br>}<br><br>// After<br>struct CachedAsyncImage&lt;Content: View, Placeholder: View&gt;: View {<br>    let url: URL?<br>    let ttlSeconds: TimeInterval<br>    let content: (Image) -&gt; Content<br>    let placeholder: () -&gt; Placeholder<br><br>    @State private var uiImage: UIImage?<br><br>    var body: some View {<br>        Group {<br>            if let uiImage { content(Image(uiImage: uiImage)) }<br>            else { placeholder() }<br>        }<br>        .task(id: url) { await load() }   // cancelled when the view goes away, restarted when url changes<br>    }<br><br>    private func load() async {<br>        uiImage = nil                                  // don&#39;t let the previous row&#39;s image linger<br>        guard let url else { return }<br>        if let cached = await ImageCache.shared.image(for: url, ttl: ttlSeconds) {<br>            uiImage = cached<br>            return<br>        }<br>        do {<br>            let (data, _) = try await URLSession.shared.data(from: url)   // the thread is released while we wait<br>            guard !Task.isCancelled,<br>                  let image = await UIImage(data: data)?.byPreparingForDisplay() else { return }  // decode finishes on a pool thread<br>            await ImageCache.shared.set(image, for: url, ttl: ttlSeconds, cost: data.count)<br>            uiImage = image<br>        } catch {}<br>    }<br>}</pre><h4>5.1 What Changed</h4><ul><li>Data(contentsOf:) → await URLSession.shared.data(from:). The thread is released while waiting.</li><li>.onAppear → .task(id: url). When the view disappears, the task is cancelled; when a reused row&#39;s url changes, the previous task is cancelled and a new one starts. URLSession&#39;s async API observes cancellation and tears down the request. The wrong-row image went away with it — no stored Task variable, no onDisappear. Resetting uiImage at the top of load() keeps the old row&#39;s image from lingering until the new one arrives.</li><li>UIImage(data:) → await byPreparingForDisplay(). Decoding is CPU work, so it finishes on a pool thread and main receives a finished bitmap. It was never going to run wider than the core count anyway.</li><li>guard !Task.isCancelled. If the row has already scrolled away by the time the response lands, skip the decode and the cache write.</li><li>DispatchQueue.main.async is gone. .task inherits the view&#39;s isolation — @MainActor, on the Xcode 15+ SDK where View is main-actor-isolated — so the line after await that assigns uiImage is already on main.</li><li>The cache became actor ImageCache. Dozens of tasks read and write it concurrently with no locks, and it gained TTL and cost-based eviction along the way.</li><li>catch {} is deliberately empty. Cancellation arrives as CancellationError, which is a normal exit, not a failure. A network failure leaves the placeholder, which is the intended behavior.</li></ul><h4>5.2 Before and After</h4><p>Measured in the reproduction project: a 200-row List, 600×600 thumbnails, a local server answering in 250 ms, a programmatic flick through all 200 rows and back (7.3 s), three runs each. iOS Simulator, iPhone 17, on an M1 Pro.</p><pre>                                                                      Before                                                          After<br>--------------------------------------------------------------------  --------------------------------------------------------------  -----------------<br>Peak thread count (baseline 11–16)                                    70–72                                                           11–13<br>Threads parked in Data(contentsOf:)                                   64–66                                                           0<br>Scroll                                                                38 fps, 2–4 stalls totaling 3.7 s; the 7.3 s flick took 10.3 s  60 fps, no stalls<br>Memory footprint                                                      28 → 158 MB                                                     28 → 32 MB<br>Requests completed / cancelled                                        274 / 0                                                         9 / 377<br>Images landing in a row whose url had changed (refresh every 400 ms)  186 of 393 (47%)                                                0<br>Requests still finishing after the scroll stopped                     9.7 s                                                           0.4 s</pre><p>A sample of the Before run during the scroll-back explains the stalls. The main thread spent 80% of those four seconds inside the Core Animation commit, in dispatch_group_wait: SwiftUI had handed an image decode to a GCD global queue and was waiting for it. Sixty-four GCD threads were parked in sendSynchronousRequest, the bottom of Data(contentsOf:). The decode couldn&#39;t start until a download finished and gave a thread back.</p><p>The memory line needs an honest footnote. The 158 MB is not thread stacks. It’s every thumbnail that ever scrolled past, downloaded, decoded and kept. After cancelled 377 of its 386 requests the moment their rows left the screen, so it decoded nine.</p><h3>6. Making Sure It Doesn’t Come Back</h3><p>Fixing it mattered less than making sure it wouldn’t reappear.</p><p>The next step in a real codebase is a search for Data(contentsOf:), String(contentsOf:), and DispatchQueue.global().async. Some hits are legitimate — a one-time read of a bundled file. The rest are this shape, synchronous I/O inside a global queue, and they get the same treatment.</p><p>What goes into the team conventions:</p><ul><li>No synchronous network calls inside DispatchQueue.global().async. Network goes through URLSession&#39;s async API or callbacks.</li><li>No synchronous I/O, semaphores, or DispatchGroup.wait() inside async functions or Task. Callback APIs get a continuation; synchronous blocking APIs go outside the pool.</li><li>In SwiftUI, async work tied to a view’s lifecycle uses .task / .task(id:), not .onAppear { Task { } }. A Task started from a UIKit cell is always stored and cancelled in prepareForReuse.</li><li>LIBDISPATCH_COOPERATIVE_POOL_STRICT=1 in the Debug scheme. A violation stops the app during development, not in production.</li><li>One item on the code review checklist: <em>“Is this work the CPU does, or work it hands off and waits for?”</em></li></ul><p>Swift 6’s strict concurrency turns some of these into compile errors. Calling NSLock.lock() from an async context is rejected; a sending closure that mutates an outer variable is rejected. But synchronous I/O like Data(contentsOf:) is invisible to the compiler. The rules and the tooling have to go together.</p><h3>Closing</h3><p>Since this bug, two questions come first whenever I look at concurrency code.</p><p><strong>1. Is this work the CPU does, or work it hands off and waits for?</strong></p><p>If the CPU does it, the core count is the ceiling. Split it if it splits; if it doesn’t, wait. Changing tools won’t make it faster.</p><p>If the CPU waits for it, let await release the thread. Then the count stops mattering.</p><p><strong>2. Is there somewhere this has to run?</strong></p><p>The main thread, or a framework’s dedicated thread. If so, keep the heavy work off it.</p><p>These two questions settle most concurrency decisions. The code in the prologue had failed the first one: waiting and working were mixed in a single closure, and the waiting half was holding a thread. That was the whole story.</p><blockquote><strong>“Which queue should this run on?” → “Is this doing work, or waiting for work?” → “If it’s waiting, why is it holding a thread?”</strong></blockquote><p>GCD asked us where to run things. Swift Concurrency asks what the thing is. Swift Concurrency didn’t give us more threads. It gave us a way to wait without one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83f11f5cd20f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pukaki-lab/why-waiting-shouldnt-cost-a-thread-83f11f5cd20f">Why Waiting Shouldn’t Cost a Thread</a> was originally published in <a href="https://medium.com/pukaki-lab">PUKAKI MAGAZINE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Swift Actors Well]]></title>
            <link>https://medium.com/pukaki-lab/how-to-use-actors-well-e473a8396f1d?source=rss----e05dc67acde4---4</link>
            <guid isPermaLink="false">https://medium.com/p/e473a8396f1d</guid>
            <category><![CDATA[thread-safe]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[swift-actor]]></category>
            <dc:creator><![CDATA[Basin]]></dc:creator>
            <pubDate>Mon, 25 May 2026 08:17:24 GMT</pubDate>
            <atom:updated>2026-05-27T06:22:00.287Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmsuc9e-9i2C5ltWUc7maw.png" /></figure><h3>Prologue: Where Actors Fit, and Why We Have to Doubt Them Again</h3><p>When you start thinking about adopting Swift Concurrency, you run into actor fairly quickly. At the entry level, the takeaway tends to fit on one line.</p><blockquote><strong><em>An </em></strong><strong><em>actor is a thread-safe class.</em></strong></blockquote><p>As a first impression, that summary isn’t bad. It just doesn’t mean an actor&#39;s methods always execute as a single atomic transaction.</p><p>And in real apps, the Source of Truth is already scattered across the server, SwiftData, UserDefaults, and ViewModels — so where exactly an actor slots into that picture isn&#39;t obvious from a one-line definition.</p><p>There are two questions I want to work through in this piece.</p><ol><li>Where does an actor <strong>fit inside an app&#39;s structure</strong>?</li><li>Once it’s there, <strong>why do we have to doubt it one more time</strong>?</li></ol><h3>1. The Question an Actor Asks</h3><h4>1.1 The Old Question — How Do We Make This Thread-Safe?</h4><p>Concurrency problems usually start like this.</p><pre>final class Counter {<br>    var value: Int = 0<br>}</pre><p>When multiple threads write value at the same time, you get a data race. So we reach for a lock, or a serial queue, or restrict access to a specific thread.</p><pre>final class Counter {<br>    private let lock = NSLock()<br>    private var value: Int = 0<br>    func increment() {<br>        lock.lock()<br>        value += 1<br>        lock.unlock()<br>    }<br>}</pre><p>The question this approach is asking is:</p><p><strong>How do we safely protect this shared state?</strong></p><p>The state is already shared across multiple places, and we protect access to that shared state after the fact.</p><h4>1.2 The Actor’s Question — Who Owns This State?</h4><p>actor changes the question.</p><pre>actor Counter {<br>    private var value: Int = 0<br>    func increment() {<br>        value += 1<br>    }<br>}</pre><p>The state inside an actor is owned by the actor. From the outside, no one can touch that state directly.</p><pre>await counter.increment()</pre><p>Outside callers can only send requests in. If the old concern was “how do we make this thread-safe?”, the question actor asks is:</p><blockquote><strong><em>Who is responsible for managing this state?</em></strong></blockquote><p>The point of actor isn&#39;t that it locks for you automatically. It&#39;s that access to the state is structurally constrained.</p><h3>2. Where Actors Belong</h3><h4>2.1 Your SOT Usually Isn’t an Actor</h4><p>The trouble is that, in real apps, most Sources of Truth aren’t inside an actor.</p><p>Take a weight-tracking app: the persistent data lives in SwiftData. No matter how cleanly you design the app around a domain-driven paradigm, the app still runs screen by screen in practice. The state that has to be shown on a screen has to live somewhere the screen can hold onto.</p><pre>@Model<br>final class WeightRecord {<br>    var date: Date<br>    var weight: Double<br>    init(date: Date, weight: Double) {<br>        self.date = date<br>        self.weight = weight<br>    }<br>}</pre><p>The state shaped for display lives in a ViewModel.</p><pre>@MainActor<br>final class WeightViewModel: ObservableObject {<br>    @Published var records: [WeightRecordViewData] = []<br>    @Published var isLoading = false<br>    @Published var errorMessage: String?<br>}</pre><p>If there’s server sync, the server may be the larger source of record. For settings, UserDefaults may be the SOT. The place actor fits is in between.</p><pre>View / ViewModel<br>- Screen state, user input, loading, errors, display-shaped data<br><br>Server / SwiftData / UserDefaults<br>- Persistent data, values that must survive an app restart<br><br>Actor<br>- In-flight state touched by multiple Tasks concurrently<br>- Caches, token refresh, downloads, file work<br>- Work with state transitions, like audio or speech recognition<br>- In-flight sync state, request deduplication</pre><p>actor is less the answer to &quot;where should this data be persisted?&quot; and more the answer to <strong>&quot;under what rules should concurrent work pass through the same mutable state?&quot;</strong></p><h4>2.2 Place 1 — Auth Token Refresh</h4><p>Imagine firing several API requests at once. The token’s expired and five requests fail simultaneously. Without an actor, five separate refresh requests could go out.</p><pre>actor AuthTokenStore {<br>    private var token: String?<br>    private var refreshTask: Task&lt;String, Error&gt;?<br><br>    func validToken() async throws -&gt; String {<br>        if let token {<br>            return token<br>        }<br>        if let refreshTask {<br>            return try await refreshTask.value<br>        }<br>        let task = Task {<br>            try await refreshTokenFromServer()<br>        }<br>        refreshTask = task<br>        do {<br>            let newToken = try await task.value<br>            token = newToken<br>            refreshTask = nil<br>            return newToken<br>        } catch {<br>            refreshTask = nil<br>            throw error<br>        }<br>    }<br>}</pre><p>The real state the actor owns here isn&#39;t token — it&#39;s refreshTask. <em>Is a refresh in flight right now? If it is, should we await its result? If it fails, how do we clean up?</em> That&#39;s the flow the actor is responsible for.</p><h4>2.3 Place 2 — Caches</h4><p>Image caches and API-response caches also fit actor well.</p><pre>actor ImageCache {<br>    private var memory: [URL: Data] = [:]<br>    func data(for url: URL) -&gt; Data? {<br>        memory[url]<br>    }<br>    func insert(_ data: Data, for url: URL) {<br>        memory[url] = data<br>    }<br>}</pre><p>The original may live on the server or on disk. The in-memory cache is temporary state touched concurrently by many screens and many Tasks. The actor becomes the owner of that memory cache.</p><h4>2.4 Place 3 — Work with State Transitions</h4><p>actor fits especially well with work that has state transitions, more so than with plain data. In a children&#39;s storybook app I built, the speech-recognition feature received events like these nearly simultaneously.</p><pre>start()<br>stop()<br>cancel()<br>timeout<br>audio interruption<br>restart</pre><p>Mix these events and the state gets tangled fast.</p><pre>actor SpeechRecognitionController {<br>    enum State {<br>        case idle<br>        case starting<br>        case recognizing<br>        case stopping<br>    }<br>    private var state: State = .idle<br><br>    func start() async {<br>        guard state == .idle else { return }<br>        state = .starting<br>        await prepareAudioSession()<br>        guard state == .starting else { return }<br>        state = .recognizing<br>    }<br><br>    func stop() {<br>        guard state == .starting || state == .recognizing else { return }<br>        state = .stopping<br>        stopRecognition()<br>        state = .idle<br>    }<br>}</pre><p>What the actor owns here isn&#39;t simple data. It&#39;s the <strong>rules of a state transition</strong> that runs idle → starting → recognizing → stopping. actor is at its most powerful when it owns flow, not just values.</p><p>But look closer at that code and there’s a subtle detail. There’s an await inside start(), and state is re-checked on either side of it. Why that re-check is needed is the subject of the next chapter.</p><h3>3. The Boundary an Actor Doesn’t Draw</h3><h4>3.1 Spatial Boundaries and Temporal Boundaries</h4><p>actor draws a spatial boundary. &quot;This state lives only inside this object; no one outside can touch it directly.&quot; That much actor gives you automatically.</p><p>What it does not give you is a temporal boundary. <em>Is the state I saw before </em><em>await still the same state after </em><em>await?</em> That question doesn&#39;t answer itself.</p><p>Drawing ownership and keeping the state inside that ownership consistent over time are two different problems. The second guard state == .starting in SpeechRecognitionController, above, was code re-drawing that temporal boundary by hand.</p><p>From here, we’ll look at how an actor falls apart when that boundary isn&#39;t drawn.</p><h4>3.2 The Trap After &quot;await&quot;</h4><p>Take the following.</p><pre>actor BankAccount {<br>    private var balance = 100<br>    func withdraw(_ amount: Int) async -&gt; Bool {<br>        guard balance &gt;= amount else {<br>            return false<br>        }<br>        await someNetworkCheck()<br>        balance -= amount<br>        return true<br>    }<br>}</pre><p>It reads naturally at first. Check whether the balance is enough, run a network check, subtract the amount. The catch is that when an actor method hits an await, the function can be suspended — and during that suspension, the actor may serve other requests.</p><pre>Task A: calls withdraw(80)<br>sees balance = 100<br>suspends at await someNetworkCheck()<br>Task B: calls withdraw(80)<br>sees balance = 100<br>suspends at await someNetworkCheck()<br>Task A resumes<br>balance -= 80<br>balance = 20<br>Task B resumes<br>balance -= 80<br>balance = -60</pre><p>The two Tasks didn’t write balance at the same time. There is no memory-level data race. Both pieces of work, though, advanced on the stale assumption that balance = 100, and that&#39;s where the logical break opens.</p><p>The Counter from the start has the same trap. As long as increment() is a single line, it&#39;s safe; the moment an await slips into it, you&#39;re in the same situation as BankAccount. What the actor keyword blocks is concurrent access — not the assumption you made before await.</p><blockquote><strong><em>Inside an </em></strong><strong><em>actor, don&#39;t trust the state you saw before </em></strong><strong><em>await to still hold after </em></strong><strong><em>await.</em></strong></blockquote><h4>3.3 Reentrancy: Why This Happens</h4><p>Swift actors are reentrant by default.</p><p><a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0306-actors.md#actor-reentrancy">swift-evolution/proposals/0306-actors.md at main · swiftlang/swift-evolution</a></p><p>When an actor method suspends at await, the actor doesn&#39;t sit idle waiting for it to resume — it can run other incoming work during that window.</p><p>This is the efficient choice. If the actor froze every time it was waiting on a network response, you&#39;d get unnecessary bottlenecks. The trade-off is that you, as the developer, have to accept that state may shift across an await.</p><pre>func doSomething() async {<br>    // the actor state I see here<br>    await something()<br>    // is not guaranteed to be the same here<br>}</pre><p>It’s safer to read await inside an actor like this:</p><p><strong>my assumption about state may have expired here.</strong></p><h4>3.4 Audio That Resumes After You Stopped It</h4><pre>actor StoryNarrationController {<br>    private var currentPage: Int?<br>    private var isPlaying = false<br><br>    func play(page: Int) async {<br>        currentPage = page<br>        isPlaying = true<br>        let audio = await loadAudio(for: page)<br>        startPlayer(with: audio)<br>    }<br><br>    func stop() {<br>        isPlaying = false<br>        stopPlayer()<br>    }<br>}</pre><p>The problem shows up in this sequence.</p><pre>play(page: 1) called<br>currentPage = 1<br>isPlaying = true<br>suspends at loadAudio(for: 1)<br>the user calls stop() during that window<br>isPlaying = false<br>stopPlayer()<br>loadAudio(for: 1) completes<br>play(page: 1) resumes<br>startPlayer()</pre><p>The user pressed stop, and the audio plays anyway. A stale async task, when it resumed, collided with the user’s most recent intent.</p><h4>3.5 Drawing Temporal Consistency by Hand</h4><p>The fix is simple at heart. <strong>After </strong><strong>await, always re-check.</strong></p><p>The most direct way is to look at the state again.</p><pre>func play(page: Int) async {<br>    currentPage = page<br>    isPlaying = true<br>    let audio = await loadAudio(for: page)<br>    guard isPlaying, currentPage == page else {<br>        return<br>    }<br>    startPlayer(with: audio)<br>}</pre><p>A slightly more general approach is to keep a version token.</p><pre>actor StoryNarrationController {<br>    private var playToken = UUID()<br><br>    func play(page: Int) async {<br>        let token = UUID()<br>        playToken = token<br>        let audio = await loadAudio(for: page)<br>        guard playToken == token else {<br>            return<br>        }<br>        startPlayer(with: audio)<br>    }<br><br>    func stop() {<br>        playToken = UUID()<br>        stopPlayer()<br>    }<br>}</pre><p>play() mints a token at its start, and after await confirms that the token is still current. If stop() or another play() fired in between, playToken has moved on, and the stale work falls away on its own. The pattern applies broadly anywhere only the latest request should count — search autocomplete, image loading, downloads, speech recognition.</p><p>Cooperative cancellation through Task.checkCancellation() solves the same problem from another angle. But cancellation operates at the Task level, so for keeping state consistent inside an actor, a version token is the more direct tool.</p><p>One last thing: keep the critical sections inside an actor short.</p><pre>func update() async {<br>    let requestID = UUID()<br>    currentRequestID = requestID<br>    state = .loading<br>    let result = await request()<br>    guard currentRequestID == requestID else {<br>        return<br>    }<br>    state = .loaded(result)<br>}</pre><p>Using an actor doesn&#39;t make the question of ordering disappear. It just gathers that question into one place.</p><h3>Closing</h3><p>Using actor well is a matter of drawing two boundaries at once.</p><p>The spatial boundary is drawn for you. actor makes &quot;who is responsible for this state&quot; structurally clear. In real apps, that owner is often not the SOT itself but the in-flight state and the workflows passing between Sources of Truth — token refresh, caches, work with state transitions, that kind of thing.</p><p>The temporal boundary is not drawn for you. Whether the state is still valid after await is something you have to confirm yourself. So actor reduces data races, but it doesn&#39;t automatically resolve logical races.</p><p>When I’m deciding whether to reach for actor, I tend to ask four things in order. If this state is screen state, a @MainActor ViewModel is more natural. If it&#39;s persistent data, the server, SwiftData, or UserDefaults is the owner, and actor doesn&#39;t replace the storage layer. If multiple Tasks touch the same in-flight state at the same time, only then does actor become a candidate. And if I need to reason about state across await inside that actor, actor alone isn&#39;t enough — re-checks, version tokens, and short critical sections have to come with it.</p><p>The shift in thinking that Swift actor asks of us fits in a single line.</p><blockquote><strong><em>“How do we make this thread-safe?” → “Who owns this state and this flow?” → “After </em></strong><strong><em>await, is this owner&#39;s state still what I assumed?&quot;</em></strong></blockquote><p>actor isn&#39;t a tool that removes concurrency. It&#39;s a tool that draws the boundary of concurrency more clearly. The better you draw both the spatial and the temporal boundary together, the simpler the app&#39;s structure gets; the worse you draw them, the more elaborate the bugs you find inside an actor.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e473a8396f1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pukaki-lab/how-to-use-actors-well-e473a8396f1d">How to Use Swift Actors Well</a> was originally published in <a href="https://medium.com/pukaki-lab">PUKAKI MAGAZINE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Color Is Not a Palette but a Formal System]]></title>
            <link>https://medium.com/pukaki-lab/color-is-not-a-palette-but-a-formal-system-0f54770ec4d9?source=rss----e05dc67acde4---4</link>
            <guid isPermaLink="false">https://medium.com/p/0f54770ec4d9</guid>
            <category><![CDATA[app-design]]></category>
            <category><![CDATA[ulm]]></category>
            <category><![CDATA[bauhaus]]></category>
            <category><![CDATA[product-design]]></category>
            <category><![CDATA[colors]]></category>
            <dc:creator><![CDATA[Basin]]></dc:creator>
            <pubDate>Fri, 22 May 2026 16:59:58 GMT</pubDate>
            <atom:updated>2026-05-22T16:59:59.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TMC-tU62ej5SJpKKq6D6tQ.png" /></figure><p>Screens don’t get complicated because they hold too much information. More often, the real problem is that the relationships between pieces of information haven’t been sorted out. When it isn’t clear what should be read first, what’s actionable right now, what’s a state and what’s just decoration, we keep adding things.</p><p>One more divider. <br>A badge. <br>An icon. <br>A caption. <br>A bigger button. <br>A stronger color.</p><p>Eventually the screen stops conveying information and starts trying to persuade the user. <br>“Look here.” <br>“Tap this.” <br>“This is important.” <br>“This is also important.” <br>“Honestly, don’t miss this one either.”</p><p>I didn’t want to make screens like that.</p><p>What I care about isn’t using more color but defining what color is <em>for</em>.<br>When color clearly takes on hierarchy, state, and affordance, the screen doesn’t need to say as much.</p><p>I didn’t start out as a designer who studied color professionally. <br>I majored in German literature, which is where I first met design as a philosophical idea, and now I work as a developer building software.<br>Maybe that’s why, when I look at color, I see structure before sensation. What matters in software isn’t the value itself but the responsibility that value carries inside the system. Color is no different. What matters more than the value .orange is whether it is action.primary, signal.warning, or simply a decoration there to recall the brand. Color values can change. Roles have to repeat across the product.</p><p>So I think of color less as a palette and more as a grammar. Color is an aesthetic choice that dresses the screen, yes, but it is also a structural rule that decides how the user reads the screen.</p><p>A user can grasp the structure of a screen before reading every sentence. That’s why, for me, color is not a palette. Color is a formal system that composes the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bzAKCV1OuXoB7eIvKPrBcg.jpeg" /></figure><h3>Color Builds Relationships, Not Moods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DyQN6pwoV7S2UrISL4G1NA.png" /><figcaption>Early on, hunting for a pretty color after the design was already done.</figcaption></figure><p>When building an app, color usually comes last.</p><p>We do the wireframes, settle the layout, organize the components, and only then say, “okay, let’s bring in the brand color.” On the actual screen, though, color isn’t a final coat of decoration. Color shifts the order in which the user reads the screen, sets distance between elements, and signals what’s available to act on.</p><p>The same text reads as the center of attention in near-black, and recedes into the background in light gray. The same card becomes part of the screen when it matches the background, and turns into an independent unit when it differs even slightly. The same button becomes a trigger for action with a strong color, and a secondary option in a neutral one.</p><p>In other words, before color carries any emotion, it creates relationships.</p><p>This view aligns naturally with the Bauhaus tradition. The Bauhaus preliminary course treated basic elements — color, form, material — as the starting point of design itself, and students trained in those fundamentals before moving into specialized workshops. Color wasn’t there to decorate a surface. It was an element that, together with form, established visual order.</p><p>An app screen, in the end, is made of points, lines, planes, type, and color. A notification dot is a point. A divider is a line. Cards and panels are planes. Typography is character, and mass. Color modulates hierarchy, tension, and state between these elements.</p><p>Used without a role, color quickly turns the screen into decoration. Used with a role, color turns the screen into structure.</p><h3>Through a Bauhaus Lens: Color Is a Basic Unit of Form</h3><p>Bringing a Bauhaus attitude into an app doesn’t mean using a lot of primary colors, or scattering circles, squares, and triangles as ornaments. What matters more is reducing the screen back down to its basic elements and looking at it that way.</p><p>Is this button just a button, or a colored plane pointing to the user’s next action? Is this card just a box for information, or a plane that has stepped one step forward inside the screen? Is this gray text less-important information, or distance that lets the eye rest? Is this red signaling an error, or building more tension than the situation needs?</p><p>Once you look at color this way, every UI element starts to look different. In a list view, for example, you don’t have to attach an icon, a sub-caption, a badge, and a divider to every row. You can organize the differences between rows through the brightness of color and the depth of planes.</p><p>The currently selected item can be revealed by surface color alone, without a separate “Selected” label. A completed item can recede with low contrast — no strike-through, no oversized check icon.</p><p>Here, color isn’t reducing information. It’s organizing the same information into fewer elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxeE6oeuq1YZg5asHRfuSA.png" /><figcaption>The new app I’m currently designing</figcaption></figure><h3>Through an Ulm Lens: Color Is a Repeatable Rule</h3><p>If Bauhaus gives us a way of seeing color and form as basic elements of design, Ulm leans closer to a way of managing those elements as a system. The Hochschule für Gestaltung Ulm (HfG Ulm) was a school in 1950s–60s Germany that researched and practiced new approaches across visual communication, industrial design, architecture, information, and film. At Ulm, design wasn’t treated as a matter of personal taste or ornament. It was treated as a methodology that had to work inside social and industrial contexts.</p><p>Choosing colors in an app is, in many ways, a similar question.</p><blockquote><strong>A color that looks pretty in one screen isn’t enough. It has to be a color that repeats with the same meaning in any situation.</strong></blockquote><p>Selected should appear the same way every time. A primary action should show up in the same color family every time. A warning should signal that confirmation is needed without manufacturing unnecessary fear. A disabled state shouldn’t look like a failure — it should simply say “not available yet.”</p><p>At Ulm, the question of looking at color shifts into this form.</p><p><em>Does this color do the same job, repeatedly, inside the system?</em></p><p>The more a color’s role repeats, the less the user has to interpret it. They just use it. That, to me, is one of the more important conditions of a good interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*vmJtL1maUrYeWDbjbZcNkQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3sk2HwrlDjw3mR477xslw.jpeg" /><figcaption>Braun 1958 transistor radio T3 / Lufthansa</figcaption></figure><h3>What Color Can Take On</h3><p>When deciding the colors of an app, I’d rather ask “what does this color need to do?” before “which color looks nice?” The jobs color can take on break down, roughly, like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdgBBxYK1dB7ij0w1xrcGg.png" /></figure><p>The point of this table is that color doesn’t work alone. It works alongside other things.</p><p>Important information, for example, doesn’t have to be expressed through darker color alone. A larger type size, more generous spacing, a more stable position, higher contrast — or, when it helps, a subtle break from the grammar you’ve been using — together build hierarchy.</p><p>If you make one color carry too many roles, the system collapses quickly.</p><p>If the brand color is used for the primary button, the selected state, categories, notifications, links, and graphs all at once, that color no longer means anything in particular. On a screen where everything looks important, nothing is.</p><h3>Primary Color Is Not the Brand Color</h3><p>In many apps, the first color anyone decides on is the brand color. And that color immediately becomes the primary color.</p><p>The logo’s color becomes the button’s color, becomes the link’s color, becomes the selection color. But brand color and primary color may not be the same thing. The brand color stands for the product’s identity. Primary color stands for the user’s next action.</p><p>Fail to make this distinction and the screen exaggerates easily. You reach for more color to show more brand, and eventually the user loses track of where to look.</p><p>In the app I’m building, I’d rather primary color didn’t behave like the protagonist. It’s enough for it to quietly point to what the user can do next. A strong color is more legible the less often it appears.</p><p>Otl Aicher’s work is a useful reference here. He took on the iconography and full graphic system for the 1972 Munich Olympics, organizing pictograms, color, grid, and typography into a single wayfinding system. The graphics there weren’t decoration meant to stand out — they were closer to a common language many people could grasp quickly.</p><p>Color in an app can work the same way. Letting people not get lost, before trying to persuade them. Sorting things into categories, before emphasizing any one of them. Letting things be read, before stimulating attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UVb81MJyBH5VcgFYxzp-YA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*jW8c4AF7510DLSxJvrr1Iw.png" /></figure><h3>A Less Stimulating App Is Not an App with Weak Color</h3><p>Making a less stimulating app doesn’t mean making every color soft. It doesn’t mean removing color, using only gray, or making everything calm regardless of context. If anything, it’s closer to the opposite.</p><p>A less stimulating app is one where the role of color is precise. The moments when strong color should appear are sorted out, neutral colors hold the base environment steady, and state colors don’t pressure the user unnecessarily.</p><p>Take error states as an example. Errors should clearly show. But not every error needs to be red at the same intensity. A problem that requires an input check and a destructive action that could lose data should carry different levels of tension. The former can do its job with a low-intensity signal color; the latter needs higher contrast and clearer wording.</p><p>The same goes for completion. Finishing something doesn’t always call for a big green banner and a celebratory animation. In some contexts, the state quietly changing is enough. The role of “completed” might be to make the user happy — or it might be to tell them they no longer need to worry about it.</p><p>“Just say the thing the situation calls for.”</p><p>That’s another principle that matters to me when working with color.</p><h3>How I Organize Color in My App</h3><p>In the app I’m building, I try to organize color by role, not by palette. Roughly like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KoKMR5MgswoNpoElmUt4_g.png" /></figure><p>Once colors are named this way, the color values themselves step back.</p><p>What matters isn’t a value like .orange — it&#39;s the role that color is carrying.</p><p>Color values can change. They may differ in light mode and dark mode, or be adjusted to meet accessibility requirements. But the roles must not change.</p><p>The more stable the roles are, the more predictable the screen becomes. The more predictable it is, the more at ease the user feels. The more at ease the user is, the more the screen can do with fewer elements.</p><h3>When Color Is Precise, the Screen Doesn’t Have to Say as Much</h3><p>I don’t think a good interface has to be quiet. Some products need to be loud, some need to push fast, some need to leave a strong impression.</p><p>But in the app I’m building, I didn’t want the screen to keep stimulating the user. More precisely, I wanted to solve with structure the problems we usually try to solve with stimulation.</p><p>Before adding a background to a button to emphasize it, I ask whether that button really needs emphasis for the user to notice it. Before making a card stand out more, I ask whether that information should sit forward on the screen at all. Before using more brand color, I ask what role that color is playing right now.</p><p>Through a Bauhaus lens, color is a formal element that works alongside shape. Through an Ulm lens, color is a repeatable function inside a system. In an app, color sits between these two perspectives.</p><p>Color isn’t the last layer that decorates the screen. It’s the first rule that lets the screen say less.</p><p>A good color system lets the user grasp the relationships on the screen before reading every word. Where the center is, what’s supporting, what’s possible to do, what to confirm. That’s why, for me, color is not a palette. Color is the product’s visual grammar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OiuFp2tvIU_kzBxR0ipIfQ.png" /><figcaption><a href="https://apps.apple.com/kz/app/turn-pomodoro-timer/id6760718734">https://apps.apple.com/kz/app/turn-pomodoro-timer/id6760718734</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f54770ec4d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pukaki-lab/color-is-not-a-palette-but-a-formal-system-0f54770ec4d9">Color Is Not a Palette but a Formal System</a> was originally published in <a href="https://medium.com/pukaki-lab">PUKAKI MAGAZINE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI, With the Grain #2 — How to Think About View and Abstraction]]></title>
            <link>https://medium.com/pukaki-lab/swiftui-with-the-grain-2-how-to-think-about-view-and-abstraction-d083eaa89c57?source=rss----e05dc67acde4---4</link>
            <guid isPermaLink="false">https://medium.com/p/d083eaa89c57</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[type-systems]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Basin]]></dc:creator>
            <pubDate>Tue, 12 May 2026 11:48:13 GMT</pubDate>
            <atom:updated>2026-05-28T08:35:24.700Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong><em>SwiftUI, With the Grain #2 — How to Think About View and Abstraction</em></strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9Ex7vWtuzcManmfbrpttw.png" /></figure><h3><strong><em>Prologue: What This Piece Is About</em></strong></h3><p><a href="https://medium.com/pukaki-lab/swiftui-with-the-grain-1-declarative-types-and-pop-want-different-things-309ac21aa3da">SwiftUI, With the Grain #1 — Declarative Types and POP Want Different Things</a></p><p>Part #1 looked at why SwiftUI’s type system makes the familiar POP-style view abstractions so hard to pull off. I also explained, briefly, why I’ve decided not to treat AnyView as a default tool.</p><p>You can lean on AnyView to mimic POP. But going that route is a fast way to drift out of the functional, declarative paradigm Apple has emphasized since SwiftUI&#39;s debut. Part #2 picks up from there.</p><p>There are two things I want to work through in this piece. In a single line: when the paradigm changes, the unit of abstraction has to change with it. The new unit isn’t a wrapper around a type — it’s structure and rules.</p><p>The abstraction a View actually needs in SwiftUI is not “abstraction that hides implementation,” but “abstraction that reuses structure.”</p><p>The urge to abstract a View behind a protocol may itself be a signal that the View is carrying too much responsibility.</p><h3><strong><em>1. Two Kinds of Abstraction</em></strong></h3><h3><strong><em>1.1 Abstraction That Hides Implementation</em></strong></h3><p>This is the kind where you put a protocol in front of a concrete type and let the caller use it knowing only the contract.</p><p>In UIKit, UIView was a class (a reference type), and there was no self-referential constraint like the one on View, so a broad protocol like protocol HomeViewProtocol: AnyObject { var view: UIView { get } } worked without friction. The point is to make a thing usable without having to pin down what it is.</p><p>This kind of abstraction usually comes in two flavors. Existential types (any P) are handed to you by the compiler as a language feature, while type-erasing wrappers like AnyView or AnySequence are explicit boxes you build by hand.</p><p>As we saw in Part #1, this pattern doesn’t translate cleanly to SwiftUI.</p><pre><em>protocol HomeViewProtocol: View { }<br>​<br>struct HomeView: HomeViewProtocol {<br>    var body: some View { Text(&quot;Home&quot;) }<br>}<br>​<br>struct ParentView: View {<br>    let child: any HomeViewProtocol<br>​<br>    var body: some View {<br>        child  // Type &#39;any HomeViewProtocol&#39; cannot conform to &#39;View&#39;<br>    }<br>}</em></pre><p>Old UIKit habits would tell you that any value satisfying the contract should slot in where any HomeViewProtocol appears. The compiler disagrees.</p><p>The root cause is what we covered in Part #1. View carries a self-referential constraint: associatedtype Body: View. Swift 5.7 lifted most of the restrictions on PAT existentials (protocols with associated types), but self-referential constraints are still off-limits as existentials. The moment you reach for any HomeViewProtocol and try to use it as a View, the Body associated type has no way to be resolved. The AnyView we saw in Part #1 §2.3 is essentially a hand-rolled escape hatch around that limitation.</p><p>That said, protocol-based hiding isn’t entirely shut down in SwiftUI. In the places Apple has carved out so callers can customize the behavior of its own standard components — ButtonStyle, LabelStyle, Layout, and so on — protocol-based hiding works just fine. But these are best read as exceptional hooks SwiftUI has opened up for itself, not as general-purpose tools. The proper SwiftUI-flavored abstractions come in 1.2, and we&#39;ll come back to these hooks at the end of that section.</p><h3><strong><em>1.2 Abstraction That Reuses Structure</em></strong></h3><p>This is the kind where you use generics, @ViewBuilder, ViewModifier, and friends to avoid repeating the same pattern. The point isn&#39;t to hide types — it&#39;s to preserve types while composing them.</p><p>SwiftUI has built up several tools along this direction. Let’s look at two of the main ones, and then briefly at the exceptional hook SwiftUI has reserved for itself.</p><p>(1) Generics — leaving a slot open for the inner view</p><pre><em>// A card component that leaves the inner View open via a generic<br>struct AppCard&lt;Content: View&gt;: View {<br>    @ViewBuilder let content: Content<br>​<br>    var body: some View {<br>        RoundedRectangle(cornerRadius: 12)<br>            .fill(.background)<br>            .shadow(radius: 4)<br>            .overlay { content }<br>    }<br>}</em></pre><p>The common “card” structure stays put, while what goes inside is left open. This is closer to reusing structure than to hiding implementation.</p><p>There’s no rule that says there can only be one slot. Just as SwiftUI itself does with Section, LabeledContent, GroupBox, and Form, you can leave several slots open at once.</p><pre><em>struct AppCard&lt;Header: View, Content: View, Footer: View&gt;: View {<br>    @ViewBuilder let header: Header<br>    @ViewBuilder let content: Content<br>    @ViewBuilder let footer: Footer<br>​<br>    var body: some View {<br>        VStack(alignment: .leading, spacing: 12) {<br>            header.font(.headline)<br>            content<br>            footer.font(.footnote).foregroundStyle(.secondary)<br>        }<br>        .padding()<br>        .background {<br>            RoundedRectangle(cornerRadius: 12).fill(.background)<br>        }<br>        .shadow(radius: 4)<br>    }<br>}</em></pre><p>(2) ViewModifier + View extension — packaging shared rules</p><pre><em>// Define the style with a ViewModifier<br>struct CardStyle: ViewModifier {<br>    func body(content: Content) -&gt; some View {<br>        content<br>            .padding()<br>            .background(.background)<br>            .cornerRadius(12)<br>            .shadow(radius: 4)<br>    }<br>}<br>​<br>// Expose it as a fluent API on View<br>extension View {<br>    func cardStyle() -&gt; some View { modifier(CardStyle()) }<br>}<br>​<br>// At the call site<br>Text(&quot;Hello&quot;).cardStyle()</em></pre><p>If you stop at the ViewModifier and don&#39;t add the extension, callers end up writing .modifier(CardStyle()), which feels off. Wrapping it in a View extension to get a fluent API is the standard pattern when you&#39;re building a design system. It lets you collect shared UI rules in one place and apply them consistently across views.</p><p>(The exception) The Style protocol pattern — a hook SwiftUI opened for its own components</p><p>I said in 1.1 that broad protocols are blocked, but in the places Apple has carved out so callers can customize the behavior of its own standard components, protocol-based hiding actually works just fine. ButtonStyle, ToggleStyle, LabelStyle, MenuStyle, ProgressViewStyle, Layout — those are the kinds of slots I mean.</p><pre>struct CapsuleButtonStyle: ButtonStyle {<br>  func makeBody(configuration: Configuration) -&gt; some View {<br>    configuration.label<br>      .padding(.horizontal, 20)<br>      .padding(.vertical, 10)<br>      .background(Capsule().fill(Color.accentColor))<br>      .foregroundColor(.white)<br>      .opacity(configuration.isPressed ? 0.7 : 1)<br>  }<br>}<br>​<br>Button(&quot;Pay&quot;) { /* handle payment */ }<br>  .buttonStyle(CapsuleButtonStyle())</pre><p>ButtonStyle also has associatedtype Body: View, but because makeBody(configuration:) returns some View, it doesn&#39;t trip the self-referential trap. The style is injected through the .buttonStyle(...) modifier, so the caller never needs to know the concrete style type.</p><p>The catch is that this pattern only works at no cost in the places SwiftUI has already laid hooks for — Button, Label, Toggle, and so on. The moment you try to roll the same pattern for your own component, you&#39;ll find that the slot holding a Configuration.label or the result of makeBody ends up having to accept an AnyView somewhere inside. The private wrapper types SwiftUI uses internally aren&#39;t reachable from user code.</p><p>So the Style protocol pattern is less a general-purpose tool and more a deliberate hook Apple opened up for its own standard components. The blockage from 1.1 is unblocked, but only inside SwiftUI’s own territory.</p><p>Why SwiftUI pushes this direction so hard</p><p>What the tools above have in common is that they preserve types. That’s not just an aesthetic preference on SwiftUI’s part — it’s an operating condition.</p><p>SwiftUI diffs the view tree on every render cycle. The unit of that diff is type identity: if the same position holds the same type, SwiftUI updates in place; if the type is different, it tears it down and recreates. So the compiler has to know the view’s type for the runtime to diff and update efficiently.</p><p>The moment you erase that type with AnyView, identity goes blurry. If the concrete payload inside an AnyView changes from branch to branch, SwiftUI may see it as a brand-new view — state gets reset, transition animations break in subtle ways. That&#39;s the mechanical reason behind the line I drew in Part #1 about not making AnyView a default tool.</p><p>The tools in 1.2 are, in the end, all abstractions for reusing things — design system components, recurring layout patterns, consistent visual rules. What’s different is the direction: not “hide the type behind a protocol,” but “compose structure and rules while keeping the type intact.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YjFe-_6eYHu2OrBusVs-CQ.png" /></figure><p>AnyView lands at the bottom of the table, but, as Part #1 argued, only as a last resort once the other tools don&#39;t fit.</p><h3><strong><em>2. When a View Has Been Given Too Much Responsibility</em></strong></h3><h3><strong><em>2.1 When the View Knows Too Much</em></strong></h3><p>Say you’re building a bill receipt in SwiftUI, and you need two variants — a regular receipt and an event receipt. Coming from UIKit, the natural move is to abstract the two variants behind a protocol.</p><pre>protocol BillReceiptViewProtocol: View {<br>    var bill: Bill { get }<br>    func requestRefund() async throws<br>    func shareBill()<br>}<br>​<br>struct DefaultBillReceiptView: BillReceiptViewProtocol {<br>    let bill: Bill<br>    ​<br>    var body: some View {<br>        VStack {<br>            Text(bill.title)<br>            Text(&quot;$\(bill.amount)&quot;)<br>            Button(&quot;Refund&quot;) { Task { try await requestRefund() } }<br>            Button(&quot;Share&quot;) { shareBill() }<br>        }<br>    }<br>    ​<br>    func requestRefund() async throws { /* regular refund API */ }<br>    func shareBill() { /* regular share */ }<br>}<br>​<br>struct EventBillReceiptView: BillReceiptViewProtocol {<br>    let bill: Bill<br>    ​<br>    var body: some View {<br>        VStack {<br>            HStack {<br>                Image(systemName: &quot;party.popper&quot;)<br>                Text(bill.title)<br>            }<br>            Text(&quot;Event discount applied&quot;).foregroundStyle(.orange)<br>            Text(&quot;$\(bill.amount)&quot;)<br>            Button(&quot;Refund&quot;) { Task { try await requestRefund() } }<br>            Button(&quot;Share&quot;) { shareBill() }<br>        }<br>    }<br>    ​<br>    func requestRefund() async throws { /* event refund API */ }<br>    func shareBill() { /* event share */ }<br>}</pre><p>The trouble shows up when you try to consume this from a parent. You hit the wall from 1.1: any BillReceiptViewProtocol can&#39;t be used as a View. You could route around it with AnyView, but I&#39;ve already laid out in Part #1 why I&#39;d rather not use that as a default tool.</p><p>So you reach for generics and try to make it work somehow.</p><pre>struct PaymentResultView&lt;Receipt: BillReceiptViewProtocol&gt;: View {<br>    let receipt: Receipt<br>    ​<br>    var body: some View {<br>        VStack {<br>            // header and other surrounding UI<br>            receipt<br>        }<br>    }<br>}<br>​<br>// At the call site<br>PaymentResultView(receipt: DefaultBillReceiptView(bill: bill))<br>PaymentResultView(receipt: EventBillReceiptView(bill: bill))</pre><p><em>Type information is preserved, and this compiles without </em><em>AnyView. It works — but you pay for it. The generic parameter spreads upward: whatever holds the </em><em>PaymentResultView either has to be generic itself or know the concrete type, and whatever holds that has the same problem. Runtime branching breaks too: an </em><em>if isEvent { EventBillReceiptView(...) } else { DefaultBillReceiptView(...) } doesn&#39;t compile, because the two branches have different types, and the only way to swap two concrete types into the same variable is to fall back to </em><em>AnyView again. On top of that, you&#39;re maintaining the protocol, the conformance on every variant, and the generic wiring at every site that touches the thing.</em></p><p>By this point, a fair question starts to surface.</p><blockquote><em>Why are we working this hard to abstract a </em>View<em> in SwiftUI?</em></blockquote><p>In UIKit, abstracting the view itself made sense because the view was a heavy object — data, state, and behavior all lived inside it, so swapping the bundle from the outside meant abstracting the view. In SwiftUI, the view doesn’t have to be that kind of heavy object. The real difference between Default and Event isn’t how it draws — it’s what it does — and that “what it does” can live outside the view.</p><p>The next section moves the abstraction down to the logic itself.</p><h3><strong>2.2 Moving the Abstraction Into the ViewModel</strong></h3><p>Rather than insisting on abstracting the view, let’s move the abstraction down to the logic — to a ViewModel. A ViewModel is a class, and there’s no self-referential constraint, so protocol abstraction works there without friction.</p><pre>protocol BillReceiptModeling: AnyObject, Observable {<br>    var bill: Bill { get }<br>    var isRefunding: Bool { get }<br>    var refundError: Error? { get }<br>    func requestRefund() async<br>    func shareBill()<br>}<br>​<br>@Observable<br>final class DefaultBillReceiptModel: BillReceiptModeling {<br>    let bill: Bill<br>    var isRefunding = false<br>    var refundError: Error?<br>​<br>    init(bill: Bill) { self.bill = bill }<br>​<br>    func requestRefund() async { /* regular refund API */ }<br>    func shareBill() { /* regular share */ }<br>}<br>​<br>@Observable<br>final class EventBillReceiptModel: BillReceiptModeling {<br>    let bill: Bill<br>    var isRefunding = false<br>    var refundError: Error?<br>​<br>    init(bill: Bill) { self.bill = bill }<br>​<br>    func requestRefund() async { /* event refund API */ }<br>    func shareBill() { /* event share */ }<br>}</pre><p>The two variants now live as two concrete ViewModel types, both conforming to the same protocol.</p><p>The views become thin display layers that receive an abstracted model and just render. No protocol attaches to the view itself.</p><pre>struct DefaultBillReceiptView: View {<br>    let model: any BillReceiptModeling<br>    ​<br>    var body: some View {<br>        VStack {<br>            Text(model.bill.title)<br>            Text(&quot;$\(model.bill.amount)&quot;)<br>            Button(&quot;Refund&quot;) { Task { await model.requestRefund() } }<br>            Button(&quot;Share&quot;) { model.shareBill() }<br>            if let error = model.refundError {<br>                Text(error.localizedDescription).foregroundStyle(.red)<br>            }<br>        }<br>    }<br>}<br>​<br>struct EventBillReceiptView: View {<br>    let model: any BillReceiptModeling<br>    ​<br>    var body: some View {<br>        VStack {<br>            HStack {<br>                Image(systemName: &quot;party.popper&quot;)<br>                Text(model.bill.title)<br>            }<br>            Text(&quot;Event discount applied&quot;).foregroundStyle(.orange)<br>            Text(&quot;$\(model.bill.amount)&quot;)<br>            Button(&quot;Refund&quot;) { Task { await model.requestRefund() } }<br>            Button(&quot;Share&quot;) { model.shareBill() }<br>            if let error = model.refundError {<br>                Text(error.localizedDescription).foregroundStyle(.red)<br>            }<br>        }<br>    }<br>}</pre><p>You inject the matching variant of the abstracted ViewModel into each view.</p><pre>DefaultBillReceiptView(model: DefaultBillReceiptModel(bill: bill))<br>EventBillReceiptView(model: EventBillReceiptModel(bill: bill))</pre><p>Branching, where you need it, goes back to a plain if/else — no generics, no AnyView.</p><pre>struct PaymentResultView: View {<br>    let bill: Bill<br>    let isEvent: Bool<br>​<br>    var body: some View {<br>        if isEvent {<br>            EventBillReceiptView(model: EventBillReceiptModel(bill: bill))<br>        } else {<br>            DefaultBillReceiptView(model: DefaultBillReceiptModel(bill: bill))<br>        }<br>    }<br>}</pre><p>The behavioral difference between the variants is now expressed at the ViewModel level, and each view turns into a thin layer that just takes a model and renders. The heavy lifting of abstraction happens where the protocol works naturally — in the ViewModel — and the views no longer need generics to participate.</p><p>The reason we were dragging generics into the view back in 2.1 was that we wanted to swap out the behavior the view was holding. Once that behavior moves into the ViewModel, the motivation to abstract the view itself disappears.</p><h3><strong>3. Closing</strong></h3><p>Put 2.1 and 2.2 side by side and one thing generalizes.</p><p>When you feel the urge to abstract a SwiftUI View behind a protocol, that urge usually isn’t a sign you’re short on abstraction tools — it’s a sign the abstraction is sitting at the wrong level.</p><p>A few questions worth pausing on when the urge shows up. Is the real difference between the variants about how they’re drawn, or about what they do? If you abstracted the model/state the view depends on instead of the view itself, would that buy you the same outcome? When you need to branch, are you swapping view variants, or are you swapping models?</p><p>Most of the time, the real difference lives on the behavior side, and the behavior can be moved out of the view. Once it has been moved, the view becomes a thin presentation layer, and the abstraction settles naturally on the model side. The view stops being the target of abstraction and becomes a result of it.</p><p>In UIKit, the view and the logic were stuck together, so the natural unit of abstraction was the bundle (protocol on View). SwiftUI unties that bundle — the view does presentation, the model does behavior and state. So the unit of abstraction shifts with it: from view down to logic, from protocol on View to protocol on Model.</p><p>TCA — a framework along similar lines</p><p>The framework that takes this line of thinking to its conclusion is <a href="https://github.com/pointfreeco/swift-composable-architecture">TCA (The Composable Architecture)</a>. In TCA, the view is defined as a function of state, and actions and side effects live in the reducer. The weight of abstraction shifts from the view down to the reducer/store layer — the same direction this piece is pointing at, just pushed further and turned into a framework choice.</p><p>That said, I don’t reach for TCA much in my own work. Someone might fairly ask why I lean on RIBs so heavily but keep TCA at arm’s length, given that the two are in roughly the same family. The reason is that I read them as pointing in different directions.</p><p>RIBs sits on top of UIKit and constrains it through simplification. It narrows the patterns you can use, makes the roles explicit, and trades expressive freedom for consistency. TCA, by contrast, extends SwiftUI: it stacks new concepts — Reducer, Store, Action — on top, broadening expressive power at the cost of learning curve and code volume. My instinct leans toward frameworks that do less (constrain) over ones that do more (extend), so RIBs fits how I work a little more naturally. That’s a matter of taste, and there are plenty of teams and projects where TCA shines. Either way, the direction this piece is pointing at — abstract at the level of logic — runs through both.</p><p>Closing out the two threads from Part #1</p><ol><li>When the paradigm changes, the unit of abstraction has to change too. The UIKit-era protocol on View becomes protocol on Model in SwiftUI.</li><li>The urge to abstract a view may itself be a signal that the view is carrying too much responsibility. If you feel that urge inside a view, it’s a sign the view is holding behavior too — move the behavior into the model, and the urge tends to go with it.</li></ol><p>To compress it into a single line: move the urge to abstract the view itself down to the level of logic, and you stop fighting SwiftUI’s grain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d083eaa89c57" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pukaki-lab/swiftui-with-the-grain-2-how-to-think-about-view-and-abstraction-d083eaa89c57">SwiftUI, With the Grain #2 — How to Think About View and Abstraction</a> was originally published in <a href="https://medium.com/pukaki-lab">PUKAKI MAGAZINE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TURN — Focus timer that follows gravity]]></title>
            <link>https://medium.com/pukaki-lab/turn-a-pomodoro-that-follows-gravity-d0b61f315b1b?source=rss----e05dc67acde4---4</link>
            <guid isPermaLink="false">https://medium.com/p/d0b61f315b1b</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[pomodoro]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[indie-apps]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Basin]]></dc:creator>
            <pubDate>Tue, 05 May 2026 06:11:35 GMT</pubDate>
            <atom:updated>2026-06-07T07:09:52.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7qMFV5ZZiwDzbLOHZKNyA.png" /></figure><p>Today we’re launching TURN, a pomodoro timer for iOS.</p><p>It’s the first app from Pukaki Lab, our small studio. More apps will follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkZBijTZEKWAhqgJqZ9Gog.png" /></figure><h3><strong>The interaction</strong></h3><p>You tilt the phone to pick a time.</p><p>Up, right, down, left — each direction holds a different duration. Maybe 25 minutes up, 50 right. You decide. To start, just tilt the phone toward the direction you want.</p><p>The idea came partly from IKEA’s KLOCKIS timer.</p><p>After a few days, your hand moves first. You stop thinking in numbers and just turn.</p><p>Even the short moment of looking at a screen and tapping can get in the way of starting. TURN takes that away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*SV7JqYCn67lwh5t2PxfChg.png" /></figure><h3><strong>Where the design comes from</strong></h3><p>We had a tradition in mind while building this.</p><p>Dieter Rams said good design is unobtrusive. TURN keeps only what a pomodoro timer needs.</p><p>Max Bill said simplicity isn’t subtraction; it’s clarity. When you open the app, only one thing is clear — that it’s time to focus.</p><p>KLOCKIS showed us that a timer can be an object you handle, not a number you adjust.</p><p>We’re not these designers. We’re not pretending to be. But we wanted TURN to belong to the same family — tools that earn their place by what they let you stop thinking about.</p><h3>Pricing</h3><p>$1.99 on the App Store. One purchase, done. No subscription, no ads, no tracking.</p><p>We chose a small price over free with in-app purchases. It felt more honest. TURN is complete on day one. If you buy it, the whole app is yours.</p><h3>Try it</h3><p><a href="https://apps.apple.com/us/app/turn-pomodoro-by-tilt/id6760718734">TURN - Pomodoro by Tilt App - App Store</a></p><p>Feedback welcome — through the App Store, Pukaki Lab Instagram, Medium comments, or email.</p><p>We’ll be writing more about how TURN was made over the coming weeks.</p><p>Thanks for reading. And if you give TURN a try, thank you for that too.</p><p>— Pukaki Lab</p><p>May 2026</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0b61f315b1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pukaki-lab/turn-a-pomodoro-that-follows-gravity-d0b61f315b1b">TURN — Focus timer that follows gravity</a> was originally published in <a href="https://medium.com/pukaki-lab">PUKAKI MAGAZINE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI, With the Grain #1 — Declarative Types and POP Want Different Things]]></title>
            <link>https://medium.com/pukaki-lab/swiftui-with-the-grain-1-declarative-types-and-pop-want-different-things-309ac21aa3da?source=rss----e05dc67acde4---4</link>
            <guid isPermaLink="false">https://medium.com/p/309ac21aa3da</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[type-systems]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Basin]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 10:54:41 GMT</pubDate>
            <atom:updated>2026-05-28T08:35:55.719Z</atom:updated>
            <content:encoded><![CDATA[<h3>SwiftUI, With the Grain #1 — Declarative Types and POP Want Different Things</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YkjCvfapkQTiRBbrnKjFkA.png" /></figure><h3>Prologue: What Felt Natural in UIKit</h3><p>In the UIKit era, abstracting a view felt like the most natural thing in the world. RIBs had ViewControllable, VIPER had PresenterOutput, and even at the simplest level, writing protocol SomeView: AnyObject and swapping implementations behind it was something we did almost out of habit. It made building design systems easier, too.</p><p>The reason this worked so smoothly is straightforward. UIViewController and UIView are both classes. Because they are reference types, polymorphism works at runtime: a variable typed as UIView can hold a UIButton instance without the compiler ever needing to know the concrete type.</p><p>Once we cross over into SwiftUI, though, the same habit starts to tangle up fast.</p><h3>1. The (Transparent) Cage Called some View</h3><h3>1.1 What an Opaque Return Type Really Is</h3><p>Whenever I try to explain SwiftUI to someone, I find myself opening up @ViewBuilder alongside the conversation. For today&#39;s topic, that lens alone should be enough.</p><p>SwiftUI’s body returns some View. Here, some means something quite different from any: it says, <em>&quot;I am returning some one specific concrete View type.&quot;</em> The return type is hidden from the caller, but at compile time it is already pinned down to exactly one thing.</p><p>Take a simple example:</p><pre>var body: some View {<br>    VStack {<br>        Text(&quot;Hello&quot;)<br>        Image(systemName: &quot;star&quot;)<br>    }<br>}</pre><p>ㄴWe write this body casually as just some View, but the compiler sees it as VStack&lt;TupleView&lt;(Text, Image)&gt;&gt;.</p><p>The same holds for more complex views.</p><pre>var body: some View {<br>    if !didBillExpire {<br>        BillReceiptView(bill: bill)<br>    } else {<br>        BillNoticeView(status: .expire, bill: bill)<br>    }<br>}</pre><p>At a glance, it looks as if the type is decided at runtime based on didBillExpire. In reality, @ViewBuilder rewrites this into something roughly like the following. (This isn&#39;t the exact compiler output — just a conceptual sketch.</p><pre>var body: _ConditionalContent&lt;BillReceiptView, BillNoticeView&gt; {<br>    if !didBillExpire {<br>        return ViewBuilder.buildEither(first: BillReceiptView(bill: bill))<br>    } else {<br>        return ViewBuilder.buildEither(second: BillNoticeView(status: .expire, bill: bill))<br>    }<br>}</pre><p>The key line is this:</p><p><em>_ConditionalContent&lt;BillReceiptView, BillNoticeView&gt;</em></p><p>Whichever branch is taken, the return type is already fixed to a single concrete type at compile time. The same is true no matter how deeply views are nested. The generics unfold recursively, and the entire view tree ends up described as one enormous type.</p><p>All of that complexity is tucked behind a single keyword — some.</p><h3>2. Why Can’t We Abstract SwiftUI Views Behind a Protocol?</h3><h3>2.1 Why Abstract at All?</h3><p>If you’ve ever thought about how to split an app into feature modules, you’ve probably seen the diagram from Tuist’s TMA (The Modular Architecture) guide.</p><p>Usually, between feature modules, we want to <strong>hide implementations and expose only interfaces.</strong> The reasoning is simple. When implementations leak across boundaries, it becomes very hard to predict the blast radius of any internal change.</p><p>When we can keep interfaces stable and rewrite internals freely, handing a refactor off to an LLM becomes much less nerve-wracking. You only need to keep your tests on the interface in good shape.</p><p>There’s a build-time benefit, too. If other modules depend directly on another module’s implementation, then (in a static-library setup) changing a single line inside that module triggers a cascade of recompilation across every module that depends on it. That cascade grows quickly with the number of modules.</p><p>Depending only on interfaces — which don’t change often — breaks the cascade. When an implementation changes, the modules that use it don’t need to rebuild. Of course, the top-level composition point where everything is wired up always rebuilds, but stopping the cascade between intermediate modules alone yields significant build-time savings.</p><h3>2.2 The Attempt That Doesn’t Work</h3><p>If you try to abstract views the way you would in UIKit, you hit a wall almost immediately.</p><pre>protocol HomeViewProtocol: View { }<br><br>struct HomeView: HomeViewProtocol {<br>    var body: some View { Text(&quot;Home&quot;) }<br>}<br><br>struct ParentView: View {<br>    let child: any HomeViewProtocol<br>    var body: some View {<br>        child  // Type &#39;any HomeViewProtocol&#39; cannot conform to &#39;View&#39;<br>    }<br>}</pre><p><em>Type &#39;any HomeViewProtocol&#39; cannot conform to &#39;View&#39;</em></p><p>HomeViewProtocol clearly inherits from View, so why this error? The answer is in the definition of the View protocol itself:</p><pre>public protocol View {<br>    associatedtype Body: View<br>    @ViewBuilder var body: Self.Body { get }<br>}</pre><p>Body is declared as an <strong>associated type.</strong> As we saw earlier, SwiftUI needs to know the concrete type of Body at compile time. The moment we wrap something as any HomeViewProtocol, that associated-type information is erased. Once erased, the type can no longer satisfy View&#39;s requirements.</p><p>Swift 5.7 relaxed many of the restrictions around existential types (any P), but for protocols with <strong>self-referential constraints</strong> like associatedtype Body: View, the wall is still standing.</p><p>To put it plainly: protocol-oriented programming wants to <strong>hide types,</strong> while SwiftUI wants to <strong>know them.</strong> That is exactly where the two collide.</p><h3>2.3 Why Apple Gave Us View, and Then Also AnyView</h3><p>Look at AnyView and something interesting stands out.</p><pre>@frozen public struct AnyView: View {<br>    public init&lt;V&gt;(_ view: V) where V: View<br>    public typealias Body = Never<br>}</pre><p>The generic parameter V appears only in the initializer; it never escapes into the rest of the type. Body is fixed to Never, effectively SwiftUI&#39;s way of saying <em>&quot;I will not track the type through </em><em>body here.&quot;</em></p><p>So AnyView becomes a <strong>type-erased view</strong> that can hold any other view inside it. Apple, in other words, carved out a deliberate escape hatch from the strictness of the type system.</p><pre>let parent = ParentView(<br>    child: AnyView(BillReceiptView(bill: bill))<br>)<br><br>struct ParentView: View {<br>    let child: AnyView<br>    var body: some View {<br>        child  // this compiles<br>    }<br>}</pre><p>At this point it starts to feel like, with AnyView in hand, anything is possible. Since the escape hatch is already there, maybe we should lean into it.</p><p>There are in fact perspectives that argue we shouldn’t be so afraid of <br>AnyView.</p><p><a href="https://medium.com/the-swift-cooperative/swiftui-why-you-need-anyview-99b1c48794a4">SwiftUI — Why You Need AnyView</a> is one of the better-known examples.</p><p>The author points out, fairly, that many developers criticize AnyView without being able to articulate <strong>why</strong> it&#39;s bad. That piece helped me think through the question one more time.</p><p>Even so, I’ve landed on not making AnyView a default tool.</p><p>Performance isn’t the main reason. The overhead of a single AnyView is, as the article argues, most likely negligible. But once it spreads throughout an app, the accumulated cost becomes hard to predict, and I&#39;d rather not build my default patterns on top of something I can&#39;t predict.</p><p>There’s a more important reason, though. The moment you wrap something in AnyView, many of the cues SwiftUI uses to <strong>judge view identity through type information</strong> grow fainter. If the concrete payload inside an AnyView changes between branches, SwiftUI may see it as a brand-new view, causing state to be reset or transition animations to break in subtle ways. These behaviors aren&#39;t always spelled out in documentation — they&#39;re the kind of thing you learn by encountering them, which makes them hard to keep consistent across a team.</p><p>The most decisive reason, though, is this: the moment AnyView becomes your default tool, you are <strong>quietly giving up the type-system benefits SwiftUI worked so hard to give you.</strong> As we saw with @ViewBuilder at the top of this piece, SwiftUI preserves type information through generics while still offering expressive flexibility through some. AnyView is convenient, but leaning on that convenience is a fast way to drift out of the functional, declarative paradigm that SwiftUI is really built around.</p><h3>Closing</h3><p>This has gone on long enough, so I’ll save the follow-up questions for the next post. Two threads I want to pick up there:</p><p>First, <strong>when the paradigm changes, the unit of abstraction has to change too.</strong> Second, <strong>the urge to abstract a view may itself be a signal that the view is carrying too much responsibility.</strong></p><p>Tied together, these two threads lead naturally into a very practical question: how should we draw module boundaries in SwiftUI? That’s where the next piece picks up.</p><p><a href="https://medium.com/pukaki-lab/swiftui-with-the-grain-2-how-to-think-about-view-and-abstraction-d083eaa89c57">SwiftUI, With the Grain #2 — How to Think About View and Abstraction</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=309ac21aa3da" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pukaki-lab/swiftui-with-the-grain-1-declarative-types-and-pop-want-different-things-309ac21aa3da">SwiftUI, With the Grain #1 — Declarative Types and POP Want Different Things</a> was originally published in <a href="https://medium.com/pukaki-lab">PUKAKI MAGAZINE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>