<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://alanquatermain.me/feed.xml" rel="self" type="application/atom+xml" /><link href="https://alanquatermain.me/" rel="alternate" type="text/html" hreflang="en" /><updated>2026-01-14T14:46:13-08:00</updated><id>https://alanquatermain.me/feed.xml</id><title type="html">AQBlog</title><subtitle>The bizarre mutterings of a 25-year Apple developer. You may find here talk of programming in Swift or Objective-C, along with other Apple-related topics. Occasionally something with more gravitas might slip through the net and make its way here. I apologise in advance...
</subtitle><author><name>Jim Dovey</name><email>jimdovey@mac.com</email></author><entry><title type="html">Interactive Fiction in Swift!</title><link href="https://alanquatermain.me/programming/technology/2025-10-03-interactive-fiction-in-swift/" rel="alternate" type="text/html" title="Interactive Fiction in Swift!" /><published>2025-10-03T09:00:00-07:00</published><updated>2025-10-03T09:00:00-07:00</updated><id>https://alanquatermain.me/programming/technology/interactive-fiction-in-swift</id><content type="html" xml:base="https://alanquatermain.me/programming/technology/2025-10-03-interactive-fiction-in-swift/"><![CDATA[<p>A few years ago I got into the Call of Cthulhu roleplaying game and discovered their single-player books, like <a href="https://www.chaosium.com/alone-against-the-dark/">Alone Against the Dark</a> and <a href="https://www.chaosium.com/alone-against-the-frost/">Alone Against the Frost</a>. I rather thought that putting together an app version with all the rules built in would be a fun project, but never had the time.</p>

<p>Recently I’ve been investigating Claude Code, and decided this would be something fun to try: a simple rules engine &amp; character sheet for CoC, and a basic choose-your-own-adventure library that I could hook up to it. I’ve been playing with those—and will provide an update here soon—but I got sidetracked. If you know me, you know just how inevitable that is.</p>

<p>This particular sidetrack can be laid at the feet of the inimitable Bill Bumgarner at Apple. When I mentioned the CYOA library I was working on, he reminded me about the old Infocom games, and I fell into the rabbit hole of the ZIL language and the ZIP virtual machine, and this immediately ignited my love of compilers, parsers, and binary file formats. Add in games and, well, I’m a goner.</p>

<!-- more -->

<p>The old Infocom games were built on a virtual machine called the <a href="https://en.wikipedia.org/wiki/Z-machine">Z-Machine</a>. This enabled them to compile a game once and write an interpreter program for each target system. Back in the late 70’s and early 80’s this was very important—there were a <em>lot</em> of <a href="https://eblong.com/infocom/#terps">different computers to support</a> in those days.</p>

<p>The games themselves were written in <a href="https://www.ifwiki.org/ZIL">ZIL</a> (the <strong>Zork Implementation Language</strong>), itself based on <a href="https://en.wikipedia.org/wiki/MDL_programming_language">MDL</a> (pronounced “muddle”), itself a version of <a href="https://en.wikipedia.org/wiki/LISP">Lisp</a>. ZIL was created and used by Infocom to develop their award-winning games, and they had tools to work with it:</p>

<ul>
  <li><strong>ZILCH</strong>: ZIL Compiler Hack. The compiler that turned ZIL code into assembly ready for the next stage:</li>
  <li><strong>ZAP</strong>: Z-Machine Assembler Program. This took assembly code (the format was itself called ZAP) and compiled it into a story file.</li>
  <li><strong>ZIP</strong>: Z-Machine Interpreter Program. This loaded the compiled story file and implemented the game interface.</li>
</ul>

<p>These, and all the various games written for the system, are well documented at <a href="https://eblong.com/infocom/">The Obsessively Complete Infocom Catalog</a> by Andrew Plotkin. Part of that catalog includes a large <a href="https://eblong.com/infocom/#terps">list of interpreters</a>, along with info on <a href="https://eblong.com/infocom/#zil">ZIL</a> and <a href="https://eblong.com/infocom/#zap">ZAP</a>. He also hosts the source code for basically all the old Infocom games, similarly to the <a href="https://github.com/historicalsource/">GitHub repo created by Jason Scott</a>, with some extra pieces.</p>

<p>Ultimately this provided a lot of useful information to feed into Claude to see what I could drum up. Specifically I wanted a library for all ZIL/ZAP/ZIP operations, along with a command-line tool that can run the compile, assemble, and run operations. This is now expanding to an auto-play command and an interactive debugger.</p>

<h2 id="semi-vibe-coding">Semi-Vibe Coding</h2>

<p>My aim has been to test the water somewhat of AI coding tools’ capabilities. So I set myself an aim of not writing any code myself, but acting as code reviewer and tester. I’ve used Claude Code for this exclusively, and feeding it the available documentation on ZIL, ZAP, and ZIP resulted in Claude being very confident in what it could create. Its confidence, while not entirely unfounded, was perhaps a little too high for the work it put together, as you’ll see.</p>

<p>One thing I definitely found useful was the use of Planning Mode. In this mode, Claude won’t attempt to make any changes to anything, but will instead create a full plan of action and present it to you for verification. Using this mode ahead of any complex task was pretty much essential, to ensure that everything went in the right direction, and helped a lot with setting up guardrails and verifying that they were indeed in place.</p>

<h3 id="the-bad">The Bad</h3>

<p>So Claude (and probably Codex too) has this thing where it’ll decide that “for now” it’ll put in a very basic stub implementation of something important, and then it’ll consider it complete because there’s code in that condition. I’ve run into this all through the project, where Claude will claim to be complete, but I’ll run and things aren’t working. I’ll check the code and there, in the middle, is a TODO or an “I’ll do it this way for now.” Sigh.</p>

<p>Another thing it often does is it’ll make code changes, announce that it’ll build/test/run, and then forget to actually do that &amp; go straight to a long description of everything that’s now in place. Meanwhile, the project doesn’t even compile. This happens relatively frequently, as it turns out.</p>

<p>One more gripe: running out of context space is painful. Whenever it compacts the conversation, it forgets completely what the command-line tool is called (it always tries to run <code class="language-plaintext highlighter-rouge">zil-interpreter</code>, when the command is <code class="language-plaintext highlighter-rouge">zil run</code>). It’ll also frequently forget the details of longer-term plans, such as the results of a comprehensive review of spec compliance. I’ve taken to asking it to write these things out as files to refer back to and update, just so all that information isn’t lost because it decided to load an entire 2000-line file several times &amp; had to dump most of its context.</p>

<h3 id="the-good">The Good</h3>

<p>That’s about it for the downside though. It’s generally providing fairly clean code, and it understands enough about parsing, lexing, ASTs, and so on that it was able to pull together the initial project very quickly. It would be able to provide detailed and cogent explanations of complex issues at both the planning phase and while debugging issues.</p>

<p>Speaking of debugging, I was frequently able to work through issues by just asking Claude to look at the code and determine why something was happening (or not happening). It sometimes took a few tries, and there were occasions where it might fixate on something unhelpful, but I was always able to get it back on track. So far there have only been about three cases where I’ve needed to look at the code myself to figure something out, which I think is pretty good. Acting as an engineering manager, this is about as much hands-on work as I’d consider appropriate for me to take on an engineer’s work.</p>

<p>One thing I found exceptionally useful was to create an agent that understood all the information about ZIL/ZAP/ZIP. It was designed &amp; prompted with the details of all the various sources of information (most of which I downloaded locally) and would serve as an advisor to the main Claude process. I needed to do a little fine-tuning here and there, because it often attempted to take on the coding tasks itself, and that wasn’t very helpful for me. In particular, you don’t actually see any output from an agent, you’ll only see requests to make edits, so it’s difficult to understand the context. In the end, I had to explicitly tell it that it’s not allowed to make code changes, but should essentially operate in planning mode.</p>

<p>The agent structure was instantly useful. Agents have their own context, so this allowed the main Claude process to keep its context free of the content of all the information handled by the agent, and it could focus entirely on the source code. I’d often have to remind it to consult with the agent, but putting in explicit guide rails (“for each task in <code class="language-plaintext highlighter-rouge">$file</code>, consult the expert to get a detailed plan, then implement that plan, then re-consult with the expert to perform code review, then repeat until approved”) generally got things running really quite nicely, and kept everything on track.</p>

<h3 id="doing-my-part">Doing My Part</h3>

<p>For my part, I’m basically doing code review. I’ll sometimes let Claude just run &amp; make multiple changes, usually when it’s doing test development, and usually with guard rails: “don’t change library code without my approval, only change the tests. Don’t assume the test expectations are correct, they may not be—ask the expert what the right output should be first.” On thornier problems, I’m often working through logic issues with Claude’s aid, checking its reasoning and expectations, and watching out for hallucination.</p>

<p>Sometimes I get the feeling that Claude is operating in a sort of fuzzy, semi-drunk cloud: it can focus in on the thing in front of it, but can end up guessing about adjacent concepts rather than just looking at the thing to understand it. It’s making a concerted effort, but it gets muddled. It’s my job to remind it to look around and learn, and to make it take notes when necessary.</p>

<p>Sometimes I would need to teach Claude about certain things, like the Swift <code class="language-plaintext highlighter-rouge">Synchronization</code> library and its <code class="language-plaintext highlighter-rouge">Mutex</code> type, or provide ways of managing state that it hadn’t considered due to its iterative-improvement flow. Things like titles for <code class="language-plaintext highlighter-rouge">@Test</code> macros, and tests with multiple inputs rather than multiple near-identical tests were other things it didn’t know about ahead of time.</p>

<p>My other main input has been to manually verify everything it claims is “complete.” As mentioned above, Claude likes to stub things in the middle of larger tasks, and totally forgets about that, or just considers that Good Enough. So I’ve wound up checking how things actually work and getting it to go back and get on track. It churned out a ZIL compiler pretty quickly, aided by some of the Infocom game repositories having both a <code class="language-plaintext highlighter-rouge">.zil</code> and a <code class="language-plaintext highlighter-rouge">.zap</code> version of the same file. This was actually incredibly helpful, because the expert agent was able to check the rules from documentation against these files to confirm what it learned. The compiler Claude created, though, had a lot of “for now” implementations though, so it was actually missing a whole bunch of functionality. I had to teach it how to determine what was missing and set up a plan.</p>

<h2 id="results">Results!</h2>

<p>The project is now up to version 0.4.3 and <a href="https://github.com/alanquatermain/swift-zil">available on GitHub</a> for perusal. Right now, the compiler needs a bunch of work (macros are now implemented but not manually tested, and we need better support for creating table-generation assembly), but Claude claims the assembler is fully spec-compliant.</p>

<p>The VM (<code class="language-plaintext highlighter-rouge">zil run &lt;game-file&gt;</code>) is actually officially done, at least for ZMachine v3 games like the Zork trilogy, Hitch-Hiker’s Guide to the Galaxy, Planetfall, and Stationfall. I’ve tried a .v5 game and it went tilt, so there’s more to fix in there, but it’s actually usable to play through the whole of Zork I already!</p>

<p>That was actually the result of a new <code class="language-plaintext highlighter-rouge">zil autoplay</code> command, which takes a game and an instruction file containing a series of commands to run, along with some directives to deal with special output cases (fights, healing, waiting until some output appears, etc.). By default it’ll wait a bit (depending how much text is in the latest output), then run a command.</p>

<p>There’s a ‘manual’ mode where you can type your own commands and press enter without typing to make it run the next step from the instruction file. You can also provide a number of seconds to wait in-between commands. Setting this to zero with the right set of instructions can get you here in no time at all:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Inside the Barrow
As you enter the barrow, the door closes inexorably behind you. Around you it
is dark, but ahead is an enormous cavern, brightly lit. Through its center
runs a wide stream. Spanning the stream is a small wooden footbridge, and
beyond a path leads into a dark tunnel. Above the bridge, floating in the air,
is a large sign. It reads:  All ye who stand before this bridge have completed
a great and perilous adventure which has tested your wit and courage. You have
mastered the first part of the ZORK trilogy. Those who pass over this bridge
must be prepared to undertake an even greater adventure that will severely
test your skill and bravery!

The ZORK trilogy continues with "ZORK II: The Wizard of Frobozz" and is
completed in "ZORK III: The Dungeon Master."
Your score is 350 (total of 350 points), in 340 moves.
This gives you the rank of Master Adventurer.

Would you like to restart the game from the beginning, restore a saved game
position, or end this session of the game?
(Type RESTART, RESTORE, or QUIT):
&gt;
</code></pre></div></div>

<p>…and in fact, that’s exactly where this text came from: <code class="language-plaintext highlighter-rouge">swift run zil autoplay zork1.z3 zork1-steps --interval 0</code>. Sometimes the Thief in the game messes things up by stealing a treasure and dumping it somewhere random, but at a zero-second command input gap, it takes barely a couple of seconds to try again.</p>

<p>I sincerely hope to get the compiler and assembler working soon, to the point where I can build and run the Zork games directly from source, then get the VM up to scratch for the latest game files.</p>

<p>Lots of fun!</p>

<p>Now I’m going to go play Zork II. Wish me luck…</p>]]></content><author><name>Jim Dovey</name><email>jimdovey@mac.com</email></author><category term="programming" /><category term="technology" /><category term="swift" /><category term="interactive-fiction" /><category term="zil" /><summary type="html"><![CDATA[A few years ago I got into the Call of Cthulhu roleplaying game and discovered their single-player books, like Alone Against the Dark and Alone Against the Frost. I rather thought that putting together an app version with all the rules built in would be a fun project, but never had the time.]]></summary></entry><entry><title type="html">Secret Sauce at MacDev|360</title><link href="https://alanquatermain.me/programming/2025-09-26-secret-sauce-macdev360/" rel="alternate" type="text/html" title="Secret Sauce at MacDev|360" /><published>2025-09-26T00:25:00-07:00</published><updated>2025-09-26T00:25:00-07:00</updated><id>https://alanquatermain.me/programming/secret-sauce-macdev360</id><content type="html" xml:base="https://alanquatermain.me/programming/2025-09-26-secret-sauce-macdev360/"><![CDATA[<p>In December 2010 I had the opportunity to speak at the MacDev|360 conference in Denver. Since this was the first big Mac-focused thing I’d had the opportunity to speak at (everything since 2008 had been all iPhone, all the time), I decided to delve into my archive somewhat and pull out the knowledge I’d gained while working on MacAdministrator, where I’d implemented OpenDirectory plugins, authorization plugins, and even <a href="/programming/2025-09-26-dynamic-patching-on-macos-x/">process injection and runtime function patching</a>.</p>

<p>When Time Machine appeared, with support built into Mail, Address Book, iPhoto, and more, there was unfortunately no API for anyone outside of Apple to use, so I took it upon myself to figure out how that was working, and to demonstrate how to integrate it into an app directly.</p>

<p>Alas, the private API parts were rather undermined by the recent release of the Mac App Store, where no private API usage would ever pass muster, but the information was there, so it seemed like it would be interesting to somebody, at least.</p>

<p>The official schedule blurb read like this:</p>

<blockquote>
  <p>Secret Sauce: How to use or duplicate Apple’s private functionality</p>

  <p>Ever wanted to hook your own data into Apple’s Managed Client infrastructure? 
Watched Address Book or iPhoto’s integration with the Time Machine user 
interface in envy? Wished you could implement your own login dialog or 
account access filters on the Macintosh? Come and See as we open the seventh 
seal and gaze deep into the workings of some of OS X’s most coveted internal &gt; workings.</p>
</blockquote>

<p>The presentation described how the system crash reporter worked—and how you could write your own. This would segue nicely into performing remote stack traces (using private API, to keep the topic more brief). Next I went through the private API used by Apple’s apps to implement an in-app Time Machine experience.</p>

<p>You can access the presentation as either PDF slides or via Keynote’s HTML viewer:</p>

<ul>
  <li><a href="/assets/presentations/secret-sauce.pdf">Download the slides (PDF)</a></li>
  <li><a href="/keynotes/secret-sauce/">Browse the Keynote presentation online</a></li>
</ul>

<p>Code used in the talk is available on Github:</p>

<ul>
  <li><a href="https://github.com/AlanQuatermain/time-machine">AQTimeMachineController (from April 2009)</a></li>
  <li><a href="https://github.com/AlanQuatermain/secret-sauce">Presentation example code</a></li>
</ul>

<p>Along with the presentation, I wrote a paper going into the same subjects in more detail, along with information on authorization and authentication, a primer on Mach messaging and the Mach Interface Generator (MiG), lots of information on the MCX managed-client system on OS X and the OpenDirectory system that underlies it, and a full write up of the Time Machine private APIs.
I had intended to do a chapter on the authorization system that lies behind all those pop-ups asking for your password, from config files through OpenDirectory and into authorization system plugins (the OS X login window UI is actually a SecurityAgent plugin that displays when the system asks to authorize the <code class="language-plaintext highlighter-rouge">system.login.console</code> right, and that right runs through a whole heap of rules to do a lot of different things). Alas, I got incredibly sick while I was trying to finish things up and spent the entire day in my room in a semi-fever, and writing this chapter was too much for me. I missed most of the conference, and had to hold onto the podium while giving my talk to avoid falling over at one point. If there’s video anywhere (there used to be, but the site isn’t live any more) then you’ll see what I’m talking about; I was in something of a fever dream throughout the presentation.</p>

<p>The paper has been on my Dropbox for the longest time, but it was only ever referenced by the presentation itself, so now it’s here in all its (unfinished) glory.</p>

<ul>
  <li><a href="/assets/papers/secret-sauce.pdf">Download the paper (PDF)</a></li>
</ul>]]></content><author><name>Jim Dovey</name><email>jimdovey@mac.com</email></author><category term="programming" /><category term="mac" /><category term="mach" /><category term="security" /><category term="conference" /><summary type="html"><![CDATA[In December 2010 I had the opportunity to speak at the MacDev|360 conference in Denver. Since this was the first big Mac-focused thing I’d had the opportunity to speak at (everything since 2008 had been all iPhone, all the time), I decided to delve into my archive somewhat and pull out the knowledge I’d gained while working on MacAdministrator, where I’d implemented OpenDirectory plugins, authorization plugins, and even process injection and runtime function patching.]]></summary></entry><entry><title type="html">Dynamic Patching on Mac OS X</title><link href="https://alanquatermain.me/programming/2025-09-26-dynamic-patching-on-macos-x/" rel="alternate" type="text/html" title="Dynamic Patching on Mac OS X" /><published>2025-09-26T00:10:00-07:00</published><updated>2025-09-26T00:10:00-07:00</updated><id>https://alanquatermain.me/programming/dynamic-patching-on-macos-x</id><content type="html" xml:base="https://alanquatermain.me/programming/2025-09-26-dynamic-patching-on-macos-x/"><![CDATA[<p>Back in the Old Times, when Macs still used PowerPC processors, I worked on 
desktop management software that needed to override core system functionality, 
for example disabling a menu item in Internet Explorer or Safari, or 
intercepting print commands to perform cost accounting. I ultimately worked out a way to inject code into other processes (we <em>were</em> running as root after all) and then patch any given function by swapping out its first instruction. When the Intel switch came, I figured out how to do the same thing for x86/IA-32.</p>

<p>The really fun part was getting it to work inside apps running via the Rosetta 
code-translation environment, which was a pretty special case. From the 
outside, the apps threads were all Intel-based, with one extra Intel thread 
running the translation process. Internally I needed to plant PowerPC code and 
patch PowerPC instructions, but where I’d normally add a new thread to do the
work, now I could only add Intel threads, so I needed a hybrid approach.</p>

<p>Eventually x86_64 came along, and this threw a spanner in the works (I found 
an instruction stream parser for i32, but not for i64). I left the company in 
2007, but in early 2009 I secured permission to share the source code and put it up on Github, along with a paper writing up the underlying theory. Since I’m going through old papers and presentations, it seems apropos to make it available here as well.</p>

<ul>
  <li><a href="/assets/papers/dynamic-patch-paper.pdf">Download the paper (PDF)</a></li>
  <li><a href="https://github.com/alanquatermain/dynamicpatch">Source on GitHub</a></li>
</ul>]]></content><author><name>Jim Dovey</name><email>jimdovey@mac.com</email></author><category term="programming" /><category term="mac" /><category term="rosetta" /><category term="reverse-engineering" /><category term="security" /><summary type="html"><![CDATA[Back in the Old Times, when Macs still used PowerPC processors, I worked on desktop management software that needed to override core system functionality, for example disabling a menu item in Internet Explorer or Safari, or intercepting print commands to perform cost accounting. I ultimately worked out a way to inject code into other processes (we were running as root after all) and then patch any given function by swapping out its first instruction. When the Intel switch came, I figured out how to do the same thing for x86/IA-32.]]></summary></entry><entry><title type="html">Rediscovered Talks, Part 2: Kobo, EPUB, and DRM</title><link href="https://alanquatermain.me/technology/epublishing/2024-09-25-rediscovered-talks-part-2/" rel="alternate" type="text/html" title="Rediscovered Talks, Part 2: Kobo, EPUB, and DRM" /><published>2024-09-25T21:00:00-07:00</published><updated>2024-09-25T21:00:00-07:00</updated><id>https://alanquatermain.me/technology/epublishing/rediscovered-talks-part-2</id><content type="html" xml:base="https://alanquatermain.me/technology/epublishing/2024-09-25-rediscovered-talks-part-2/"><![CDATA[<p>This second batch of unearthed slides comes from my years at Kobo, where I led the team that created the Kobo iOS app, then went on to work on standards conformance issues. I wound up taking part in working groups at the IDPF and the W3C, helping stitch together EPUB standards and tried (mostly failed) to get web browsers to properly implement the things that page-layout eBooks would need, rather than dynamically-sized websites.</p>

<p>I wound up involved in the DRM conversation after the IDPF put out a <a href="https://idpf.org/epub-content-protection-rfp">Request for Proposals</a> looking for implementations of ‘lightweight’ DRM that would provide some sort of standard for managing library loans in the digital age. As someone with a personal interest in <em>not</em> having DRM get in the way of All The Things, I promptly designed a system that I felt would satisfy everyone involved. It was well-enough received that I wound up becoming intrinsically linked to eBook DRM, moderating a panel at a W3C workshop, and giving talks to the National Information Standards Organization and others. By this time the Readium SDK project had been announced, and we were looking at providing all the infrastructure necessary for anyone to build on top of the ePub3 standard.</p>

<h3 id="w3c-digital-publishing-workshop-2013--drm-panel-moderation">W3C Digital Publishing Workshop 2013 — DRM panel moderation</h3>
<p>In February 2013 the W3C hosted a digital publishing workshop in New York, bringing together publishers, tech companies, and standards folks to figure out how ebooks should behave on the open web. I moderated a session on DRM, guiding a panel through the tension between protecting content and keeping it interoperable. The deck I used to frame that discussion is now archived here, in a version that actually includes the presenter notes. I’ve also included a direct link to the minutes of the discussion, as there was some interesting conversation happening during the Q&amp;A portion.</p>

<p>I wrote about this back when it happened, and wrote a lot more about the ideas behind the proposal. You can <a href="/technology/epublishing/2013-02-14-ebook-drm-and-undrm/">find that post here</a>. I’m also now hosting the position paper <a href="/assets/papers/Kobo-EPUB-LCP.pdf">locally here</a> rather than on Dropbox.</p>

<ul>
  <li><a href="/assets/presentations/W3CeBooksDRMSession.pdf">Download the slides (PDF)</a></li>
  <li><a href="https://www.w3.org/2013/02/12-ebooks-minutes.html#item02">Read the Minutes</a></li>
</ul>

<h3 id="niso-webinar-2013--epub3-and-interoperability">NISO Webinar 2013 — EPUB3 and interoperability</h3>
<p>A couple of months later, NISO invited me to speak about what libraries needed to know as EPub3 adoption ramped up. The talk dug into practical questions I was hearing from librarians and vendors: how DRM wrapped around EPUB files, what interoperability really meant, and where Kobo saw the format heading. I’ve included the slides below along with the still-live event page for context.</p>

<ul>
  <li><a href="/assets/presentations/NISO-DRM.pdf">Download the slides (PDF)</a></li>
  <li><a href="https://www.niso.org/events/2013/04/epub3-and-future-interoperable-e-books-what-libraries-need-know">Webinar overview</a></li>
</ul>

<p>If you’ve ever worked on ebook distribution you’ll recognise many of the sticking points captured in these decks. It’s a nice reminder of how much of that discussion is still relevant today, even as the tooling has matured.</p>]]></content><author><name>Jim Dovey</name><email>jimdovey@mac.com</email></author><category term="technology" /><category term="epublishing" /><category term="drm" /><category term="epub" /><category term="talks" /><summary type="html"><![CDATA[This second batch of unearthed slides comes from my years at Kobo, where I led the team that created the Kobo iOS app, then went on to work on standards conformance issues. I wound up taking part in working groups at the IDPF and the W3C, helping stitch together EPUB standards and tried (mostly failed) to get web browsers to properly implement the things that page-layout eBooks would need, rather than dynamically-sized websites.]]></summary></entry><entry><title type="html">Rediscovered Talks, Part 1: Networking the Early iOS World</title><link href="https://alanquatermain.me/programming/technology/2024-09-25-rediscovered-talks-part-1/" rel="alternate" type="text/html" title="Rediscovered Talks, Part 1: Networking the Early iOS World" /><published>2024-09-25T20:00:00-07:00</published><updated>2024-09-25T20:00:00-07:00</updated><id>https://alanquatermain.me/programming/technology/rediscovered-talks-part-1</id><content type="html" xml:base="https://alanquatermain.me/programming/technology/2024-09-25-rediscovered-talks-part-1/"><![CDATA[<p>I’ve been digging through old files lately—stuff in dropbox and on old hard drives—and realised I’d done quite a few presentations in the past for which there’s just about nothing available online. Here’s a couple that deal with iOS 4 and 5 APIs. I worked a lot with networking and data handling at this time, so I’d run into all the bad situations head-on and had to work out solutions on my own, and I’d get to talk about that sometimes.</p>

<h3 id="fitc-mobile-2010--optimised-networking-and-data-handling-in-ios-4">FITC Mobile 2010 — Optimised networking and data handling in iOS 4</h3>

<p>In September 2010 I got to speak at <a href="https://fitc.ca/event/mobile2010/">FITC Mobile</a> about networking and concurrency. My talk focused properly asynchronous network coding, the Foundation and CoreFoundation networking APIs, and streaming large data requests, focusing on a case study of the Outpost app and how it could reasonably handle 120MB XML responses on the original iPhone. I also went into some detail about the then-new Grand Central Dispatch APIs, and how to determine network availability properly.</p>

<ul>
  <li><a href="/keynotes/FITCMobile/index.html">View Online</a></li>
  <li><a href="/assets/presentations/FITCMobile2010.pdf">Download the slides (PDF)</a></li>
</ul>

<h3 id="toronto-cocoaheads--file-coordination-in-practice">Toronto CocoaHeads — File coordination in practice</h3>

<p>Around the same period I presented an evening talk at the Toronto CocoaHeads meetup, walking through the File Coordination APIs, and how to manage simultaneous file accessacross multiple threads and processes. These were new APIs, and I’d been investigating them for my book on Objective-C and had learned a lot. The deck goes into detail on why the API exists, and how it solves all these problems, before closing with a discussion of how to use it to implement sanitized iCloud document handling.</p>

<ul>
  <li><a href="/assets/presentations/FileCoordination.pdf">Download the slides (PDF)</a></li>
</ul>

<p>Pulling these out reminded me how much fun that era of iPhone and iPad development really was. If you end up reading through them, let me know what else you’d like me to unearth—I’ve got a lot more archives to go.</p>]]></content><author><name>Jim Dovey</name><email>jimdovey@mac.com</email></author><category term="programming" /><category term="technology" /><category term="ios" /><category term="networking" /><category term="talks" /><summary type="html"><![CDATA[I’ve been digging through old files lately—stuff in dropbox and on old hard drives—and realised I’d done quite a few presentations in the past for which there’s just about nothing available online. Here’s a couple that deal with iOS 4 and 5 APIs. I worked a lot with networking and data handling at this time, so I’d run into all the bad situations head-on and had to work out solutions on my own, and I’d get to talk about that sometimes.]]></summary></entry><entry><title type="html">Visual Effect Views in SwiftUI</title><link href="https://alanquatermain.me/programming/swiftui/2019-11-18-VisualEffectView/" rel="alternate" type="text/html" title="Visual Effect Views in SwiftUI" /><published>2019-11-18T00:00:00-08:00</published><updated>2019-11-18T00:00:00-08:00</updated><id>https://alanquatermain.me/programming/swiftui/VisualEffectView</id><content type="html" xml:base="https://alanquatermain.me/programming/swiftui/2019-11-18-VisualEffectView/"><![CDATA[<p>One of the key elements of the new UI styles introduced in iOS 8 and macOS 10.10 was the use of transparency, specifically a blurred semitransparent background through which some of the underlying content could be seen. On iOS, this is implemented using a <code class="language-plaintext highlighter-rouge">UIVisualEffectView</code>, while on macOS the same can be obtained using an <code class="language-plaintext highlighter-rouge">NSVisualEffectView</code>. The two are somewhat different in the types of inputs they take, however, and their APIs don’t quite match up with one another.</p>

<p>This seems like something SwiftUI could fix, though, right? Somewhat like the way <code class="language-plaintext highlighter-rouge">List</code>, <code class="language-plaintext highlighter-rouge">Form</code>, and <code class="language-plaintext highlighter-rouge">Button</code> in SwiftUI each describe the same <em>behavior</em>, but with different <em>implementation</em> on different operating systems. What’s more, it really sounds like it’d be an ideal modifier rather than a plain view type: you’re more likely to want to do this:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">VStack</span> <span class="p">{</span>
    <span class="kt">Text</span><span class="p">(</span><span class="s">"Hello, World"</span><span class="p">)</span>
    <span class="o">...</span>
<span class="p">}</span>
<span class="o">.</span><span class="nf">visualEffect</span><span class="p">(</span><span class="o">.</span><span class="n">systemBlur</span><span class="p">)</span>
</code></pre></div></div>

<p>…than this:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">VisualEffect</span><span class="p">(</span><span class="o">.</span><span class="n">systemBlur</span><span class="p">)</span> <span class="p">{</span>
    <span class="kt">VStack</span> <span class="p">{</span>
        <span class="kt">Text</span><span class="p">(</span><span class="s">"Hello, World"</span><span class="p">)</span>
        <span class="o">...</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Sadly, SwiftUI doesn’t provide us with an API for this.</p>

<p>Happily, that gives us a chance to delve into the implementation of a nicely complex <code class="language-plaintext highlighter-rouge">View</code> type with multi-platform support. We can even look at the use of custom environment values and preference keys as a means of modifying a visual effect applied elsewhere in the view hierarchy.</p>

<p>The ideal API is the one described above, where a visual effect is applied to an existing view as a modifier. These are actually quite straightforward to add, requiring little more than an extension on <code class="language-plaintext highlighter-rouge">View</code>. Since visual effects are generally used as backgrounds, this will ultimately wrap the <code class="language-plaintext highlighter-rouge">.background()</code> modifier, supplying some private view type:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">extension</span> <span class="kt">View</span> <span class="p">{</span>
    <span class="kd">public</span> <span class="kd">func</span> <span class="nf">visualEffect</span><span class="p">(</span><span class="nv">effect</span><span class="p">:</span> <span class="kt">VisualEffect</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kd">some</span> <span class="kt">View</span> <span class="p">{</span>
        <span class="nf">background</span><span class="p">(</span><span class="kt">VisualEffectView</span><span class="p">(</span><span class="nv">effect</span><span class="p">:</span> <span class="n">effect</span><span class="p">))</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>That’s a pretty straightforward API I think, but there’s one wrinkle visible: what’s a <code class="language-plaintext highlighter-rouge">VisualEffect</code>? When we look at <code class="language-plaintext highlighter-rouge">NSVisualEffectView</code> and <code class="language-plaintext highlighter-rouge">UIVisualEffectView</code>, they take quite different parameters:</p>

<h4 id="macos">macOS</h4>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">open</span> <span class="kd">class</span> <span class="kt">NSVisualEffectView</span> <span class="p">:</span> <span class="kt">NSView</span> <span class="p">{</span>
    <span class="kd">open</span> <span class="k">var</span> <span class="nv">material</span><span class="p">:</span> <span class="kt">NSVisualEffectView</span><span class="o">.</span><span class="kt">Material</span>
    <span class="kd">open</span> <span class="k">var</span> <span class="nv">blendingMode</span><span class="p">:</span> <span class="kt">NSVisualEffectView</span><span class="o">.</span><span class="kt">BlendingMode</span>
    <span class="kd">open</span> <span class="k">var</span> <span class="nv">state</span><span class="p">:</span> <span class="kt">NSVisualEffectView</span><span class="o">.</span><span class="kt">State</span>
    <span class="kd">open</span> <span class="k">var</span> <span class="nv">isEmphasized</span><span class="p">:</span> <span class="kt">Bool</span>
<span class="p">}</span>
</code></pre></div></div>

<h4 id="ios">iOS</h4>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">open</span> <span class="kd">class</span> <span class="kt">UIVisualEffectView</span><span class="p">:</span> <span class="kt">UIView</span><span class="p">,</span> <span class="kt">NSSecureCoding</span> <span class="p">{</span>
    <span class="kd">@NSCopying</span> <span class="kd">open</span> <span class="k">var</span> <span class="nv">effect</span><span class="p">:</span> <span class="kt">UIVisualEffect</span><span class="p">?</span>
<span class="p">}</span>

<span class="kd">open</span> <span class="kd">class</span> <span class="kt">UIVisualEffect</span> <span class="p">:</span> <span class="kt">NSObject</span><span class="p">,</span> <span class="kt">NSCopying</span><span class="p">,</span> <span class="kt">NSSecureCoding</span> <span class="p">{</span>
<span class="p">}</span>

<span class="kd">open</span> <span class="kd">class</span> <span class="kt">UIBlurEffect</span> <span class="p">:</span> <span class="kt">UIVisualEffect</span> <span class="p">{</span>
    <span class="kd">public</span> <span class="nf">init</span><span class="p">(</span><span class="nv">style</span><span class="p">:</span> <span class="kt">UIBlurEffect</span><span class="o">.</span><span class="kt">Style</span><span class="p">)</span>
<span class="p">}</span>

<span class="kd">open</span> <span class="kd">class</span> <span class="kt">UIVibrancyEffect</span><span class="p">:</span> <span class="kt">UIVisualEffect</span> <span class="p">{</span>
    <span class="kd">public</span> <span class="nf">init</span><span class="p">(</span><span class="nv">blurEffect</span><span class="p">:</span> <span class="kt">UIBlurEffect</span><span class="p">)</span>
    <span class="kd">public</span> <span class="nf">init</span><span class="p">(</span><span class="nv">blurEffect</span><span class="p">:</span> <span class="kt">UIBlurEffect</span><span class="p">,</span> <span class="nv">style</span><span class="p">:</span> <span class="kt">UIVibrancyEffect</span><span class="o">.</span><span class="kt">Style</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Those are quite different, and we don’t particularly want to expose that at the level of the view modifier API, so we’re going to encapsulate them inside a new <code class="language-plaintext highlighter-rouge">VisualEffect</code> type.</p>

<h2 id="a-cross-platform-visualeffect">A cross-platform <code class="language-plaintext highlighter-rouge">VisualEffect</code></h2>

<p>Our <code class="language-plaintext highlighter-rouge">VisualEffect</code> type will be an <code class="language-plaintext highlighter-rouge">enum</code>, and it will contain another <code class="language-plaintext highlighter-rouge">enum</code> defining the material types available. On iOS five types of system material will be available, while on macOS the underlying system uses semantic values. Several of these semantic values refer to items already available to SwiftUI, such as menus, popovers, tooltips, and the like. So here we’ll include only the ones that lend themselves to other uses.</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">enum</span> <span class="kt">VisualEffect</span><span class="p">:</span> <span class="kt">Equatable</span><span class="p">,</span> <span class="kt">Hashable</span> <span class="p">{</span>
    <span class="kd">public</span> <span class="kd">enum</span> <span class="kt">Material</span><span class="p">:</span> <span class="kt">Equatable</span><span class="p">,</span> <span class="kt">Hashable</span> <span class="p">{</span>
        <span class="c1">// Available on all platforms.</span>
        <span class="k">case</span> <span class="p">`</span><span class="nv">default</span><span class="p">`</span>
        
        <span class="c1">// Only on iOS-based platforms.</span>
        <span class="k">case</span> <span class="n">ultraThin</span>
        <span class="k">case</span> <span class="n">thin</span>
        <span class="k">case</span> <span class="n">thick</span>
        <span class="k">case</span> <span class="n">chrome</span>
        
        <span class="c1">// Only on macOS.</span>
        <span class="k">case</span> <span class="n">titlebar</span>
        <span class="k">case</span> <span class="n">windowBackground</span>
        <span class="k">case</span> <span class="nf">headerView</span><span class="p">(</span><span class="nv">behindWindow</span><span class="p">:</span> <span class="kt">Bool</span><span class="p">)</span>
        <span class="k">case</span> <span class="nf">contentBackground</span><span class="p">(</span><span class="nv">behindWindow</span><span class="p">:</span> <span class="kt">Bool</span><span class="p">)</span>
        <span class="k">case</span> <span class="nf">behindPageBackground</span><span class="p">(</span><span class="nv">behindWindow</span><span class="p">:</span> <span class="kt">Bool</span><span class="p">)</span>
    <span class="p">}</span>
    
    <span class="c1">// Some default types.</span>
    <span class="k">case</span> <span class="n">system</span>
    <span class="k">case</span> <span class="n">systemLight</span>
    <span class="k">case</span> <span class="n">systemDark</span>
    
    <span class="c1">// Configurable types.</span>
    <span class="k">case</span> <span class="nf">adaptive</span><span class="p">(</span><span class="kt">Material</span><span class="p">)</span>
    <span class="k">case</span> <span class="nf">light</span><span class="p">(</span><span class="kt">Material</span><span class="p">)</span>
    <span class="k">case</span> <span class="nf">dark</span><span class="p">(</span><span class="kt">Material</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Here we have the basics down. The <code class="language-plaintext highlighter-rouge">VisualEffect</code> type contains three catch-all cases which cover most eventualities: <code class="language-plaintext highlighter-rouge">system</code> will use a basic material that will change based on the current <code class="language-plaintext highlighter-rouge">colorScheme</code>. <code class="language-plaintext highlighter-rouge">systemLight</code> and <code class="language-plaintext highlighter-rouge">systemDark</code> will use the same basic material but will fix either a light or dark color scheme for their own appearance.</p>

<p>Beyond this, there are three primary cases: <code class="language-plaintext highlighter-rouge">adaptive</code>, <code class="language-plaintext highlighter-rouge">light</code>, and <code class="language-plaintext highlighter-rouge">dark</code>. The three <code class="language-plaintext highlighter-rouge">system</code> cases essentially map to <code class="language-plaintext highlighter-rouge">adaptive(.default)</code>, <code class="language-plaintext highlighter-rouge">light(.default)</code>, and <code class="language-plaintext highlighter-rouge">dark(.default)</code>. These three allow the specification of particular material types.</p>

<p>The materials themselves are defined in a sub-<code class="language-plaintext highlighter-rouge">enum</code>, <code class="language-plaintext highlighter-rouge">Material</code>. This contains a single type that provides a useful default on all platforms, named <code class="language-plaintext highlighter-rouge">default</code>, appropriately enough. The various thickness-based materials from iOS are then only available on iOS (tvOS doesn’t actually support these, but we’ll just silently use <code class="language-plaintext highlighter-rouge">.default</code> on that platform), while macOS’s semantic materials follow. If you look at the <a href="https://github.com/AlanQuatermain/AQUI/blob/master/Sources/AQUI/VisualEffectView.swift#L48">full implementation</a> you’ll see a lot of <code class="language-plaintext highlighter-rouge">@available</code> macros marking all these platform-specific pieces; for the sake of readability I’ve left these out of the samples here.</p>

<p>So, now we have a way for clients of our API to specify an effect. How do we go from that to a platform-specific type? We’ll implement an extension on <code class="language-plaintext highlighter-rouge">VisualEffect</code> for each differing platform that vends an appropriate platform-specific value. These are all going to be internal implementation details, and will consist of exclusively <code class="language-plaintext highlighter-rouge">internal</code> and <code class="language-plaintext highlighter-rouge">private</code> methods.</p>

<h3 id="ios-1">iOS</h3>

<p>We’ll sidestep the whole issue of <code class="language-plaintext highlighter-rouge">UIVibrancyEffect</code> for now, and leave that for a future update. Right now we’ll stick to using <code class="language-plaintext highlighter-rouge">UIBlurEffect</code>, and we can map the materials directly across. Since <code class="language-plaintext highlighter-rouge">UIBlurEffect</code> takes a single input parameter, most of the work falls to a single private property to map from our <code class="language-plaintext highlighter-rouge">enum</code> to the appropriate <code class="language-plaintext highlighter-rouge">UIBlurEffect.Style</code>.</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">extension</span> <span class="kt">VisualEffect</span> <span class="p">{</span>
    <span class="k">var</span> <span class="nv">parameters</span><span class="p">:</span> <span class="kt">UIVisualEffect</span> <span class="p">{</span> <span class="kt">UIBlurEffect</span><span class="p">(</span><span class="nv">style</span><span class="p">:</span> <span class="k">self</span><span class="o">.</span><span class="n">blurStyle</span><span class="p">)</span> <span class="p">}</span>
    
    <span class="kd">private</span> <span class="k">var</span> <span class="nv">blurStyle</span><span class="p">:</span> <span class="kt">UIBlurEffect</span><span class="o">.</span><span class="kt">Style</span> <span class="p">{</span>
        <span class="k">switch</span> <span class="k">self</span> <span class="p">{</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">system</span><span class="p">:</span>      <span class="k">return</span> <span class="o">.</span><span class="n">systemMaterial</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">systemLight</span><span class="p">:</span> <span class="k">return</span> <span class="o">.</span><span class="n">systemMaterialLight</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">systemDark</span><span class="p">:</span>  <span class="k">return</span> <span class="o">.</span><span class="n">systemMaterialDark</span>
        <span class="k">case</span> <span class="o">.</span><span class="nf">adaptive</span><span class="p">(</span><span class="k">let</span> <span class="nv">material</span><span class="p">):</span>
            <span class="k">switch</span> <span class="n">material</span> <span class="p">{</span>
            <span class="k">case</span> <span class="o">.</span><span class="nv">ultraThin</span><span class="p">:</span>    <span class="k">return</span> <span class="o">.</span><span class="n">systemUltraThinMaterial</span>
            <span class="k">case</span> <span class="o">.</span><span class="nv">thin</span><span class="p">:</span>         <span class="k">return</span> <span class="o">.</span><span class="n">systemThinMaterial</span>
            <span class="k">case</span> <span class="o">.</span><span class="k">default</span><span class="p">:</span>      <span class="k">return</span> <span class="o">.</span><span class="n">systemMaterial</span>
            <span class="k">case</span> <span class="o">.</span><span class="nv">thick</span><span class="p">:</span>        <span class="k">return</span> <span class="o">.</span><span class="n">systemThickMaterial</span>
            <span class="k">case</span> <span class="o">.</span><span class="nv">chrome</span><span class="p">:</span>       <span class="k">return</span> <span class="o">.</span><span class="n">systemChromeMaterial</span>
            <span class="p">}</span>
        <span class="k">case</span> <span class="o">.</span><span class="nf">light</span><span class="p">(</span><span class="k">let</span> <span class="nv">material</span><span class="p">):</span>
            <span class="k">switch</span> <span class="n">material</span> <span class="p">{</span>
            <span class="k">case</span> <span class="o">.</span><span class="nv">ultraThin</span><span class="p">:</span>    <span class="k">return</span> <span class="o">.</span><span class="n">systemUltraThinMaterialLight</span>
            <span class="k">case</span> <span class="o">.</span><span class="nv">thin</span><span class="p">:</span>         <span class="k">return</span> <span class="o">.</span><span class="n">systemThinMaterialLight</span>
            <span class="k">case</span> <span class="o">.</span><span class="k">default</span><span class="p">:</span>      <span class="k">return</span> <span class="o">.</span><span class="n">systemMaterialLight</span>
            <span class="k">case</span> <span class="o">.</span><span class="nv">thick</span><span class="p">:</span>        <span class="k">return</span> <span class="o">.</span><span class="n">systemThickMaterialLight</span>
            <span class="k">case</span> <span class="o">.</span><span class="nv">chrome</span><span class="p">:</span>       <span class="k">return</span> <span class="o">.</span><span class="n">systemChromeMaterialLight</span>
            <span class="p">}</span>
        <span class="k">case</span> <span class="o">.</span><span class="nf">dark</span><span class="p">(</span><span class="k">let</span> <span class="nv">material</span><span class="p">):</span>
            <span class="k">switch</span> <span class="n">material</span> <span class="p">{</span>
            <span class="k">case</span> <span class="o">.</span><span class="nv">ultraThin</span><span class="p">:</span>    <span class="k">return</span> <span class="o">.</span><span class="n">systemUltraThinMaterialDark</span>
            <span class="k">case</span> <span class="o">.</span><span class="nv">thin</span><span class="p">:</span>         <span class="k">return</span> <span class="o">.</span><span class="n">systemThinMaterialDark</span>
            <span class="k">case</span> <span class="o">.</span><span class="k">default</span><span class="p">:</span>      <span class="k">return</span> <span class="o">.</span><span class="n">systemMaterialDark</span>
            <span class="k">case</span> <span class="o">.</span><span class="nv">thick</span><span class="p">:</span>        <span class="k">return</span> <span class="o">.</span><span class="n">systemThickMaterialDark</span>
            <span class="k">case</span> <span class="o">.</span><span class="nv">chrome</span><span class="p">:</span>       <span class="k">return</span> <span class="o">.</span><span class="n">systemChromeMaterialDark</span>
            <span class="p">}</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The three ‘default’ values are quickly handled, while the remainder have their constituent materials broken out and mapped to the appropriate UIKit values.</p>

<h3 id="tvos">tvOS</h3>

<p>It turns out that tvOS doesn’t support the various <code class="language-plaintext highlighter-rouge">systemMaterial</code> types available in iOS, and only has the original <code class="language-plaintext highlighter-rouge">regular</code>, <code class="language-plaintext highlighter-rouge">light</code>, and <code class="language-plaintext highlighter-rouge">dark</code> options available. In the interest of increased code sharing between iOS and tvOS code, we’ll allow the same options to be input on tvOS, but we’ll map them all to these three basic materials, ignoring the attached <code class="language-plaintext highlighter-rouge">Material</code> type when the OS doesn’t support them.</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">extension</span> <span class="kt">VisualEffect</span> <span class="p">{</span>
    <span class="k">var</span> <span class="nv">parameters</span><span class="p">:</span> <span class="kt">UIVisualEffect</span> <span class="p">{</span>
        <span class="k">switch</span> <span class="k">self</span> <span class="p">{</span>
        <span class="k">case</span> <span class="o">.</span><span class="n">adaptive</span><span class="p">,</span> <span class="o">.</span><span class="nv">system</span><span class="p">:</span>   <span class="k">return</span> <span class="kt">UIBlurEffect</span><span class="p">(</span><span class="nv">style</span><span class="p">:</span> <span class="o">.</span><span class="n">regular</span><span class="p">)</span>
        <span class="k">case</span> <span class="o">.</span><span class="n">light</span><span class="p">,</span> <span class="o">.</span><span class="nv">systemLight</span><span class="p">:</span> <span class="k">return</span> <span class="kt">UIBlurEffect</span><span class="p">(</span><span class="nv">style</span><span class="p">:</span> <span class="o">.</span><span class="n">light</span><span class="p">)</span>
        <span class="k">case</span> <span class="o">.</span><span class="n">dark</span><span class="p">,</span> <span class="o">.</span><span class="nv">systemDark</span><span class="p">:</span>   <span class="k">return</span> <span class="kt">UIBlurEffect</span><span class="p">(</span><span class="nv">style</span><span class="p">:</span> <span class="o">.</span><span class="n">dark</span><span class="p">)</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="macos-1">macOS</h3>

<p>On macOS there’s a little more work to be done. The visual effect itself is defined not only by a material, but by a choice of what content to use in calculating the blur: should it use content from within the window, similar to the Safari titlebar, or behind the view, like the Finder sidebar? Beyond this, there are no material values related to color schemes, so specifying an explicit light or dark style requires the use of a specific <code class="language-plaintext highlighter-rouge">NSAppearance</code> instance. There are more options here than just ‘light’ and ‘dark,’ but until SwiftUI makes the various contrast options available for inspection somehow we’ll stick to using those two via the <code class="language-plaintext highlighter-rouge">.aqua</code> and <code class="language-plaintext highlighter-rouge">.darkAqua</code> values.</p>

<p>All together, that’s three separate parameters that need to be passed to the underlying <code class="language-plaintext highlighter-rouge">NSVisualEffectView</code>. Our extension, then, will start by defining a type for that:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">extension</span> <span class="kt">VisualEffect</span> <span class="p">{</span>
    <span class="kd">struct</span> <span class="kt">NSEffectParameters</span> <span class="p">{</span>
        <span class="k">var</span> <span class="nv">material</span><span class="p">:</span> <span class="kt">NSVisualEffectView</span><span class="o">.</span><span class="kt">Material</span> <span class="o">=</span> <span class="o">.</span><span class="n">contentBackground</span>
        <span class="k">var</span> <span class="nv">blendingMode</span><span class="p">:</span> <span class="kt">NSVisualEffectView</span><span class="o">.</span><span class="kt">BlendingMode</span> <span class="o">=</span> <span class="o">.</span><span class="n">behindWindow</span>
        <span class="k">var</span> <span class="nv">appearance</span><span class="p">:</span> <span class="kt">NSAppearance</span><span class="p">?</span> <span class="o">=</span> <span class="kc">nil</span>
    <span class="p">}</span>
    
    <span class="c1">// ...</span>
<span class="p">}</span>
</code></pre></div></div>

<p>By declaring a structure type with default values for all its properties, we can simplify the declaration of the <code class="language-plaintext highlighter-rouge">system</code> family of effects; they refer to these default values defined in <code class="language-plaintext highlighter-rouge">NSEffectParameters</code>.</p>

<p>Next we need to extract an appropriate <code class="language-plaintext highlighter-rouge">NSVisualEffectView.Material</code> from our <code class="language-plaintext highlighter-rouge">VisualEffect</code>:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">private</span> <span class="k">var</span> <span class="nv">material</span><span class="p">:</span> <span class="kt">NSVisualEffectView</span><span class="o">.</span><span class="kt">Material</span> <span class="p">{</span>
    <span class="k">switch</span> <span class="k">self</span> <span class="p">{</span>
    <span class="k">case</span> <span class="o">.</span><span class="n">system</span><span class="p">,</span> <span class="o">.</span><span class="n">systemLight</span><span class="p">,</span> <span class="o">.</span><span class="nv">systemDark</span><span class="p">:</span>
        <span class="k">return</span> <span class="o">.</span><span class="n">contentBackground</span>
    <span class="k">case</span> <span class="o">.</span><span class="nf">adaptive</span><span class="p">(</span><span class="k">let</span> <span class="nv">material</span><span class="p">),</span> <span class="o">.</span><span class="nf">light</span><span class="p">(</span><span class="k">let</span> <span class="nv">material</span><span class="p">),</span> <span class="o">.</span><span class="nf">dark</span><span class="p">(</span><span class="k">let</span> <span class="nv">material</span><span class="p">):</span>
        <span class="k">switch</span> <span class="n">material</span> <span class="p">{</span>
        <span class="k">case</span> <span class="o">.</span><span class="k">default</span><span class="p">,</span> <span class="o">.</span><span class="nv">contentBackground</span><span class="p">:</span> <span class="k">return</span> <span class="o">.</span><span class="n">contentBackground</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">titlebar</span><span class="p">:</span> <span class="k">return</span> <span class="o">.</span><span class="n">titlebar</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">headerView</span><span class="p">:</span> <span class="k">return</span> <span class="o">.</span><span class="n">headerView</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">behindPageBackground</span><span class="p">:</span> <span class="k">return</span> <span class="o">.</span><span class="n">underPageBackground</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">windowBackground</span><span class="p">:</span> <span class="k">return</span> <span class="o">.</span><span class="n">windowBackground</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This makes use of Swift’s ability to extract similar types from multiple matched cases in a single expression. This lets us ignore the <code class="language-plaintext highlighter-rouge">adaptive</code>, <code class="language-plaintext highlighter-rouge">light</code>, and <code class="language-plaintext highlighter-rouge">dark</code> parts of the effect specification, and look only at the attached materials, and do so without duplicating any code.</p>

<p>Next is the blending mode. This is implicit in some places (<code class="language-plaintext highlighter-rouge">titlebar</code> uses within-window content like Safari, while <code class="language-plaintext highlighter-rouge">windowBackground</code> uses behind-window content like the Finder sidebar), but explicit in most:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">private</span> <span class="k">var</span> <span class="nv">blendingMode</span><span class="p">:</span> <span class="kt">NSVisualEffectView</span><span class="o">.</span><span class="kt">BlendingMode</span> <span class="p">{</span>
    <span class="k">switch</span> <span class="k">self</span> <span class="p">{</span>
    <span class="k">case</span> <span class="o">.</span><span class="n">system</span><span class="p">,</span> <span class="o">.</span><span class="n">systemLight</span><span class="p">,</span> <span class="o">.</span><span class="nv">systemDark</span><span class="p">:</span>
        <span class="k">return</span> <span class="o">.</span><span class="n">behindWindow</span>
    <span class="k">case</span> <span class="o">.</span><span class="nf">adaptive</span><span class="p">(</span><span class="k">let</span> <span class="nv">material</span><span class="p">),</span>
         <span class="o">.</span><span class="nf">light</span><span class="p">(</span><span class="k">let</span> <span class="nv">material</span><span class="p">),</span>
         <span class="o">.</span><span class="nf">dark</span><span class="p">(</span><span class="k">let</span> <span class="nv">material</span><span class="p">):</span>
        <span class="k">switch</span> <span class="n">material</span> <span class="p">{</span>
        <span class="k">case</span> <span class="o">.</span><span class="k">default</span><span class="p">,</span> <span class="o">.</span><span class="nv">windowBackground</span><span class="p">:</span>
            <span class="k">return</span> <span class="o">.</span><span class="n">behindWindow</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">titlebar</span><span class="p">:</span>
            <span class="k">return</span> <span class="o">.</span><span class="n">withinWindow</span>
        <span class="k">case</span> <span class="o">.</span><span class="nf">contentBackground</span><span class="p">(</span><span class="k">let</span> <span class="nv">b</span><span class="p">),</span>
             <span class="o">.</span><span class="nf">headerView</span><span class="p">(</span><span class="k">let</span> <span class="nv">b</span><span class="p">),</span>
             <span class="o">.</span><span class="nf">behindPageBackground</span><span class="p">(</span><span class="k">let</span> <span class="nv">b</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">b</span> <span class="p">?</span> <span class="o">.</span><span class="nv">behindWindow</span> <span class="p">:</span> <span class="o">.</span><span class="n">withinWindow</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>With these pieces in place, we can define the <code class="language-plaintext highlighter-rouge">parameters</code> property itself:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">var</span> <span class="nv">parameters</span><span class="p">:</span> <span class="kt">NSEffectParameters</span> <span class="p">{</span>
    <span class="k">switch</span> <span class="k">self</span> <span class="p">{</span>
    <span class="k">case</span> <span class="o">.</span><span class="nv">system</span><span class="p">:</span>
        <span class="k">return</span> <span class="kt">NSEffectParameters</span><span class="p">()</span>
    <span class="k">case</span> <span class="o">.</span><span class="nv">systemLight</span><span class="p">:</span>
        <span class="k">return</span> <span class="kt">NSEffectParameters</span><span class="p">(</span><span class="nv">appearance</span><span class="p">:</span> <span class="kt">NSAppearance</span><span class="p">(</span><span class="nv">named</span><span class="p">:</span> <span class="o">.</span><span class="n">aqua</span><span class="p">))</span>
    <span class="k">case</span> <span class="o">.</span><span class="nv">systemDark</span><span class="p">:</span>
        <span class="k">return</span> <span class="kt">NSEffectParameters</span><span class="p">(</span><span class="nv">appearance</span><span class="p">:</span> <span class="kt">NSAppearance</span><span class="p">(</span><span class="nv">named</span><span class="p">:</span> <span class="o">.</span><span class="n">darkAqua</span><span class="p">))</span>
    <span class="k">case</span> <span class="o">.</span><span class="nv">adaptive</span><span class="p">:</span>
        <span class="k">return</span> <span class="kt">NSEffectParameters</span><span class="p">(</span><span class="nv">material</span><span class="p">:</span> <span class="k">self</span><span class="o">.</span><span class="n">material</span><span class="p">,</span>
                                  <span class="nv">blendingMode</span><span class="p">:</span> <span class="k">self</span><span class="o">.</span><span class="n">blendingMode</span><span class="p">)</span>
    <span class="k">case</span> <span class="o">.</span><span class="nv">light</span><span class="p">:</span>
        <span class="k">return</span> <span class="kt">NSEffectParameters</span><span class="p">(</span><span class="nv">material</span><span class="p">:</span> <span class="k">self</span><span class="o">.</span><span class="n">material</span><span class="p">,</span>
                                  <span class="nv">blendingMode</span><span class="p">:</span> <span class="k">self</span><span class="o">.</span><span class="n">blendingMode</span><span class="p">,</span>
                                  <span class="nv">appearance</span><span class="p">:</span> <span class="kt">NSAppearance</span><span class="p">(</span><span class="nv">named</span><span class="p">:</span> <span class="o">.</span><span class="n">aqua</span><span class="p">))</span>
    <span class="k">case</span> <span class="o">.</span><span class="nv">dark</span><span class="p">:</span>
        <span class="k">return</span> <span class="kt">NSEffectParameters</span><span class="p">(</span><span class="nv">material</span><span class="p">:</span> <span class="k">self</span><span class="o">.</span><span class="n">material</span><span class="p">,</span>
                                  <span class="nv">blendingMode</span><span class="p">:</span> <span class="k">self</span><span class="o">.</span><span class="n">blendingMode</span><span class="p">,</span>
                                  <span class="nv">appearance</span><span class="p">:</span> <span class="kt">NSAppearance</span><span class="p">(</span><span class="nv">named</span><span class="p">:</span> <span class="o">.</span><span class="n">darkAqua</span><span class="p">))</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Now we’re ready to tackle the view itself.</p>

<h2 id="defining-environment-values-and-preference-keys">Defining environment values and preference keys</h2>

<p>We’d like to see our <code class="language-plaintext highlighter-rouge">VisualEffect</code> settings propagate downwards using the SwiftUI environment, and at the same time we’d like descendants to request a change to any visual effect ancestors when necessary. For the former, there are two steps to perform, and one for the latter.</p>

<p>To see what’s required to create new environment values, take a look at the <code class="language-plaintext highlighter-rouge">EnvironmentValues</code> type itself:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">struct</span> <span class="kt">EnvironmentValues</span> <span class="p">{</span>
    <span class="kd">public</span> <span class="nf">init</span><span class="p">()</span>
    <span class="kd">public</span> <span class="kd">subscript</span><span class="o">&lt;</span><span class="kt">K</span><span class="o">&gt;</span><span class="p">(</span><span class="nv">key</span><span class="p">:</span> <span class="kt">K</span><span class="o">.</span><span class="k">Type</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">K</span><span class="o">.</span><span class="kt">Value</span> <span class="k">where</span> <span class="kt">K</span> <span class="p">:</span> <span class="kt">EnvironmentKey</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">EnvironmentValues</code> type handily provides key-value storage for us, and uses <em>types</em> as the keys. You define a type conforming to <code class="language-plaintext highlighter-rouge">EnvironmentKey</code>, and its own type serves as a key, while the value type it represents is defined as an associated type:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">protocol</span> <span class="kt">EnvironmentKey</span> <span class="p">{</span>
    <span class="kd">associatedtype</span> <span class="kt">Value</span>
    <span class="kd">static</span> <span class="k">var</span> <span class="nv">defaultValue</span><span class="p">:</span> <span class="k">Self</span><span class="o">.</span><span class="kt">Value</span> <span class="p">{</span> <span class="k">get</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>To house a <code class="language-plaintext highlighter-rouge">VisualEffect</code> within the environment then, we first need to define the key type. We’ll use a <code class="language-plaintext highlighter-rouge">Value</code> of <code class="language-plaintext highlighter-rouge">VisualEffect?</code>, and a default value of <code class="language-plaintext highlighter-rouge">nil</code>. Our views will interpret a <code class="language-plaintext highlighter-rouge">nil</code> value to mean that the visual effect should be disabled.</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">struct</span> <span class="kt">VisualEffectKey</span><span class="p">:</span> <span class="kt">EnvironmentKey</span> <span class="p">{</span>
    <span class="kd">typealias</span> <span class="kt">Value</span> <span class="o">=</span> <span class="kt">VisualEffect</span><span class="p">?</span>
    <span class="kd">static</span> <span class="k">var</span> <span class="nv">defaultValue</span><span class="p">:</span> <span class="kt">Value</span> <span class="o">=</span> <span class="kc">nil</span>
<span class="p">}</span>
</code></pre></div></div>

<p>To actually store the value, it needs to be written into the <code class="language-plaintext highlighter-rouge">EnvironmentValues</code> instance via that type’s <code class="language-plaintext highlighter-rouge">subscript</code> modifier. This is easy to accomplish with an extension:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">extension</span> <span class="kt">EnvironmentValues</span> <span class="p">{</span>
    <span class="kd">public</span> <span class="k">var</span> <span class="nv">visualEffect</span><span class="p">:</span> <span class="kt">VisualEffect</span><span class="p">?</span> <span class="p">{</span>
        <span class="k">get</span> <span class="p">{</span> <span class="k">self</span><span class="p">[</span><span class="kt">VisualEffectKey</span><span class="o">.</span><span class="k">self</span><span class="p">]</span> <span class="p">}</span>
        <span class="k">set</span> <span class="p">{</span> <span class="k">self</span><span class="p">[</span><span class="kt">VisualEffectKey</span><span class="o">.</span><span class="k">self</span><span class="p">]</span> <span class="o">=</span> <span class="n">newValue</span> <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The preference key type is similar to the environment key, with one extra difference: preference keys are designed to be reduced from a graph down to a single value. This allows a single ancestor to adopt one value even when several descendants each publish their own versions. The <code class="language-plaintext highlighter-rouge">PreferenceKey</code> type, then, needs to implement a <code class="language-plaintext highlighter-rouge">reduce</code> method. In our case, we’ll go with a simple case: a non-nil value overrides a nil value, and a non-nil value can’t be overridden.</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">struct</span> <span class="kt">VisualEffectPreferenceKey</span><span class="p">:</span> <span class="kt">PreferenceKey</span> <span class="p">{</span>
    <span class="kd">typealias</span> <span class="kt">Value</span> <span class="o">=</span> <span class="kt">VisualEffect</span><span class="p">?</span>
    <span class="kd">static</span> <span class="k">var</span> <span class="nv">defaultValue</span><span class="p">:</span> <span class="kt">VisualEffect</span><span class="p">?</span> <span class="o">=</span> <span class="kc">nil</span>
    
    <span class="kd">static</span> <span class="kd">func</span> <span class="nf">reduce</span><span class="p">(</span><span class="nv">value</span><span class="p">:</span> <span class="k">inout</span> <span class="kt">VisualEffect</span><span class="p">?,</span> <span class="nv">nextValue</span><span class="p">:</span> <span class="p">()</span> <span class="o">-&gt;</span> <span class="kt">VisualEffect</span><span class="p">?)</span> <span class="p">{</span>
        <span class="k">guard</span> <span class="n">value</span> <span class="o">==</span> <span class="kc">nil</span> <span class="k">else</span> <span class="p">{</span> <span class="k">return</span> <span class="p">}</span>
        <span class="n">value</span> <span class="o">=</span> <span class="nf">nextValue</span><span class="p">()</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>With these items in place, we’re ready to tackle the view itself.</p>

<h2 id="wrapping-a-platform-visualeffectview">Wrapping a platform VisualEffectView</h2>

<p>Our approach is going to use a plain SwiftUI <code class="language-plaintext highlighter-rouge">View</code> type that itself wraps a platform specific <code class="language-plaintext highlighter-rouge">ViewRepresentable</code> type. The outer view will hold onto a copy of the specified <code class="language-plaintext highlighter-rouge">VisualEffect</code> in a <code class="language-plaintext highlighter-rouge">@State</code> property, and will then place that value into the environment of the platform-specific view in its <code class="language-plaintext highlighter-rouge">body</code>. It will also install a preference monitor using the <code class="language-plaintext highlighter-rouge">onPreferenceChange(key:perform:)</code> modifier to pick up any changes to the effect requested by descendants. These changes will be used to update its <code class="language-plaintext highlighter-rouge">@State</code> property, triggering a refresh of the view and a corresponding change to the environment.</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">struct</span> <span class="kt">VisualEffectView</span><span class="p">:</span> <span class="kt">View</span> <span class="p">{</span>
    <span class="kd">@State</span> <span class="kd">private</span> <span class="k">var</span> <span class="nv">effect</span><span class="p">:</span> <span class="kt">VisualEffect</span><span class="p">?</span>
    <span class="kd">private</span> <span class="k">let</span> <span class="nv">content</span><span class="p">:</span> <span class="n">_PlatformVisualEffectView</span>
    
    <span class="k">var</span> <span class="nv">body</span><span class="p">:</span> <span class="kd">some</span> <span class="kt">View</span> <span class="p">{</span>
        <span class="n">content</span>
            <span class="o">.</span><span class="nf">environment</span><span class="p">(\</span><span class="o">.</span><span class="n">visualEffect</span><span class="p">,</span> <span class="n">effect</span><span class="p">)</span>
            <span class="o">.</span><span class="nf">onPreferenceChange</span><span class="p">(</span><span class="kt">VisualEffectPreferenceKey</span><span class="o">.</span><span class="k">self</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">self</span><span class="o">.</span><span class="n">effect</span> <span class="o">=</span> <span class="nv">$0</span>
            <span class="p">}</span>
    <span class="p">}</span>
    
    <span class="kd">fileprivate</span> <span class="nf">init</span><span class="p">(</span><span class="nv">effect</span><span class="p">:</span> <span class="kt">VisualEffect</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">self</span><span class="o">.</span><span class="n">_effect</span> <span class="o">=</span> <span class="kt">State</span><span class="p">(</span><span class="nv">wrappedValue</span><span class="p">:</span> <span class="n">effect</span><span class="p">)</span>
        <span class="k">self</span><span class="o">.</span><span class="n">content</span> <span class="o">=</span> <span class="nf">_PlatformVisualEffectView</span><span class="p">()</span>
    <span class="p">}</span>
    
    <span class="c1">// ...</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Note that the initializer here has to initialize the <code class="language-plaintext highlighter-rouge">State&lt;VisualEffect?&gt;</code> property named <code class="language-plaintext highlighter-rouge">_effect</code>; the compiler would generally synthesize this, but since we’re defining our own initializer we have to reach behind the curtain a little to get things set up properly.</p>

<p>The <code class="language-plaintext highlighter-rouge">_PlatformVisualEffectView</code> will be implemented as an inner type separately for macOS and iOS/tvOS, with each conforming to their respective platforms’ <code class="language-plaintext highlighter-rouge">ViewRepresentable</code> types. The implementations are selected via <code class="language-plaintext highlighter-rouge">#if os()</code> expressions, defining which will be compiled.</p>

<p>Let’s start with iOS, which is simpler.</p>

<h3 id="iostvos">iOS/tvOS</h3>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">private</span> <span class="kd">struct</span> <span class="nv">_PlatformVisualEffectView</span><span class="p">:</span> <span class="kt">UIViewRepresentable</span> <span class="p">{</span>
    <span class="kd">func</span> <span class="nf">makeUIView</span><span class="p">(</span><span class="nv">context</span><span class="p">:</span> <span class="kt">Context</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">UIVisualEffectView</span> <span class="p">{</span>
        <span class="k">let</span> <span class="nv">effect</span> <span class="o">=</span> <span class="n">context</span><span class="o">.</span><span class="n">environment</span><span class="o">.</span><span class="n">visualEffect</span> <span class="p">??</span> <span class="o">.</span><span class="n">system</span>
        
        <span class="k">let</span> <span class="nv">view</span> <span class="o">=</span> <span class="kt">UIVisualEffectView</span><span class="p">(</span><span class="nv">effect</span><span class="p">:</span> <span class="n">effect</span><span class="o">.</span><span class="n">parameters</span><span class="p">)</span>
        <span class="n">view</span><span class="o">.</span><span class="n">autoresizingMask</span> <span class="o">=</span> <span class="p">[</span><span class="o">.</span><span class="n">flexibleWidth</span><span class="p">,</span> <span class="o">.</span><span class="n">flexibleHeight</span><span class="p">]</span>
        <span class="k">return</span> <span class="n">view</span>
    <span class="p">}</span>
    
    <span class="kd">func</span> <span class="nf">updateUIView</span><span class="p">(</span><span class="n">_</span> <span class="nv">uiView</span><span class="p">:</span> <span class="kt">UIVisualEffectView</span><span class="p">,</span> <span class="nv">context</span><span class="p">:</span> <span class="kt">Context</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">guard</span> <span class="k">let</span> <span class="nv">effect</span> <span class="o">=</span> <span class="n">context</span><span class="o">.</span><span class="n">environment</span><span class="o">.</span><span class="n">visualEffect</span> <span class="k">else</span> <span class="p">{</span>
            <span class="c1">// disable the effect</span>
            <span class="n">uiView</span><span class="o">.</span><span class="n">isHidden</span> <span class="o">=</span> <span class="kc">true</span>
            <span class="k">return</span>
        <span class="p">}</span>
        
        <span class="n">uiView</span><span class="o">.</span><span class="n">isHidden</span> <span class="o">=</span> <span class="kc">false</span>
        <span class="n">uiView</span><span class="o">.</span><span class="n">effect</span> <span class="o">=</span> <span class="n">effect</span><span class="o">.</span><span class="n">parameters</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>We’ve implemented the two required methods, <code class="language-plaintext highlighter-rouge">makeUIView(context:)</code> and <code class="language-plaintext highlighter-rouge">updateUIView(_:context:)</code>. In both cases, the effect to use is read from the environment. In <code class="language-plaintext highlighter-rouge">makeUIView</code> a valid effect is required to initialize the underlying view, so a default is used if the environment contains <code class="language-plaintext highlighter-rouge">nil</code>. In <code class="language-plaintext highlighter-rouge">updateUIView</code> a <code class="language-plaintext highlighter-rouge">nil</code> value from the environment causes the effect view to be hidden. Any non-nil value is passed on to the underlying <code class="language-plaintext highlighter-rouge">UIVisualEffectView</code> instance.</p>

<h3 id="macos-2">macOS</h3>

<p>On macOS there’s a little more work to do, but not much:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">private</span> <span class="kd">struct</span> <span class="nv">_PlatformVisualEffectView</span><span class="p">:</span> <span class="kt">NSViewRepresentable</span> <span class="p">{</span>
    <span class="kd">func</span> <span class="nf">makeNSView</span><span class="p">(</span><span class="nv">context</span><span class="p">:</span> <span class="kt">Context</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">NSVisualEffectView</span> <span class="p">{</span>
        <span class="k">let</span> <span class="nv">view</span> <span class="o">=</span> <span class="kt">NSVisualEffectView</span><span class="p">()</span>
        <span class="n">view</span><span class="o">.</span><span class="n">autoresizingMask</span> <span class="o">=</span> <span class="p">[</span><span class="o">.</span><span class="n">width</span><span class="p">,</span> <span class="o">.</span><span class="n">height</span><span class="p">]</span>
        <span class="k">return</span> <span class="n">view</span>
    <span class="p">}</span>
    
    <span class="kd">func</span> <span class="nf">updateNSView</span><span class="p">(</span><span class="n">_</span> <span class="nv">nsView</span><span class="p">:</span> <span class="kt">NSVisualEffectView</span><span class="p">,</span> <span class="nv">context</span><span class="p">:</span> <span class="kt">Context</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">guard</span> <span class="k">let</span> <span class="nv">params</span> <span class="o">=</span> <span class="n">context</span><span class="o">.</span><span class="n">environment</span><span class="o">.</span><span class="n">visualEffect</span><span class="p">?</span><span class="o">.</span><span class="n">parameters</span> <span class="k">else</span> <span class="p">{</span>
            <span class="c1">// disable the effect</span>
            <span class="n">nsView</span><span class="o">.</span><span class="n">isHidden</span> <span class="o">=</span> <span class="kc">true</span>
            <span class="k">return</span>
        <span class="p">}</span>
        <span class="n">nsView</span><span class="o">.</span><span class="n">isHidden</span> <span class="o">=</span> <span class="kc">false</span>
        <span class="n">nsView</span><span class="o">.</span><span class="n">material</span> <span class="o">=</span> <span class="n">params</span><span class="o">.</span><span class="n">material</span>
        <span class="n">nsView</span><span class="o">.</span><span class="n">blendingMode</span> <span class="o">=</span> <span class="n">params</span><span class="o">.</span><span class="n">blendingMode</span>
        <span class="n">nsView</span><span class="o">.</span><span class="n">appearance</span> <span class="o">=</span> <span class="n">params</span><span class="o">.</span><span class="n">appearance</span>
        
        <span class="c1">// mark emphasized if it contains the first responder</span>
        <span class="k">if</span> <span class="k">let</span> <span class="nv">resp</span> <span class="o">=</span> <span class="n">nsView</span><span class="o">.</span><span class="n">window</span><span class="p">?</span><span class="o">.</span><span class="n">firstResponder</span> <span class="k">as?</span> <span class="kt">NSView</span> <span class="p">{</span>
            <span class="n">nsView</span><span class="o">.</span><span class="n">isEmphasized</span> <span class="o">=</span> <span class="n">resp</span> <span class="o">===</span> <span class="n">nsView</span> <span class="o">||</span> <span class="n">resp</span><span class="o">.</span><span class="nf">isDescendant</span><span class="p">(</span><span class="nv">of</span><span class="p">:</span> <span class="n">nsView</span><span class="p">)</span>
        <span class="p">}</span>
        <span class="k">else</span> <span class="p">{</span>
            <span class="n">nsView</span><span class="o">.</span><span class="n">isEmphasized</span> <span class="o">=</span> <span class="kc">false</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>In <code class="language-plaintext highlighter-rouge">makeNSView(context:)</code> the setup is more straightforward than for iOS, as the <code class="language-plaintext highlighter-rouge">NSVisualEffectView</code> doesn’t require its effects to be specified at initialization. That means that the bulk of the work happens in <code class="language-plaintext highlighter-rouge">updateNSView(_:context:)</code>. Here again the effect is read from the environment, and any <code class="language-plaintext highlighter-rouge">nil</code> value found causes the effect view to be hidden. If a value is present, its constituents—<code class="language-plaintext highlighter-rouge">material</code>, <code class="language-plaintext highlighter-rouge">blendingMode</code>, and optional <code class="language-plaintext highlighter-rouge">appearance</code>—are assigned to the underlying view.</p>

<p>Additionally, effect views on macOS have an additional <code class="language-plaintext highlighter-rouge">isEmphasized</code> property that’s designed to help indicate when a view contains the first responder. We’re hiding this complexity from our SwiftUI clients by looking at the view hierarchy to determine if the first responder is within the effect view. If so, it adopts the emphasized appearance, and turns it off if not.</p>

<p>At this point, your implementation is just about complete. It only remains to implement the view modifier APIs for assigning an effect and publishing an effect preference.</p>

<h2 id="wrapping-it-up">Wrapping it up</h2>

<p>The actual public API you’re about to implement may seem like an anticlimax. It ultimately consists of six lines of code, two of which are the function names, and two more are closing braces. However, this speaks to the way in which the complexity of the underlying platform-specific interface has been tucked away out of sight: everything is there in a single one-line function call, even in the internal interface.</p>

<p>Without further ado, here’s what you need to put it all to together:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">extension</span> <span class="kt">View</span> <span class="p">{</span>
    <span class="kd">public</span> <span class="kd">func</span> <span class="nf">visualEffect</span><span class="p">(</span><span class="n">_</span> <span class="nv">effect</span><span class="p">:</span> <span class="kt">VisualEffect</span> <span class="o">=</span> <span class="o">.</span><span class="n">system</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kd">some</span> <span class="kt">View</span> <span class="p">{</span>
        <span class="nf">background</span><span class="p">(</span><span class="kt">VisualEffectView</span><span class="p">(</span><span class="nv">effect</span><span class="p">:</span> <span class="n">effect</span><span class="p">))</span>
    <span class="p">}</span>
    
    <span class="kd">public</span> <span class="kd">func</span> <span class="nf">visualEffectPreference</span><span class="p">(</span><span class="n">_</span> <span class="nv">effect</span><span class="p">:</span> <span class="kt">VisualEffect</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kd">some</span> <span class="kt">View</span> <span class="p">{</span>
        <span class="nf">preference</span><span class="p">(</span><span class="nv">key</span><span class="p">:</span> <span class="kt">VisualEffectPreferenceKey</span><span class="o">.</span><span class="k">self</span><span class="p">,</span> <span class="nv">value</span><span class="p">:</span> <span class="n">effect</span><span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And that’s it.</p>

<p>The full source, with all its documentation and copious availability attributes, is available as part of <a href="https://github.com/AlanQuatermain/AQUI">AQUI on Github</a>. If you encounter any trouble, please file an issue there and I’ll be sure to take a look asap.</p>]]></content><author><name>Jim Dovey</name><email>jimdovey@mac.com</email></author><category term="programming" /><category term="swiftui" /><category term="swift" /><category term="ios" /><category term="macos" /><category term="apple" /><summary type="html"><![CDATA[One of the key elements of the new UI styles introduced in iOS 8 and macOS 10.10 was the use of transparency, specifically a blurred semitransparent background through which some of the underlying content could be seen. On iOS, this is implemented using a UIVisualEffectView, while on macOS the same can be obtained using an NSVisualEffectView. The two are somewhat different in the types of inputs they take, however, and their APIs don’t quite match up with one another.]]></summary></entry><entry><title type="html">SwiftUI Bindings with CoreData</title><link href="https://alanquatermain.me/programming/swiftui/2019-11-15-CoreData-and-bindings/" rel="alternate" type="text/html" title="SwiftUI Bindings with CoreData" /><published>2019-11-15T00:00:00-08:00</published><updated>2019-11-15T00:00:00-08:00</updated><id>https://alanquatermain.me/programming/swiftui/CoreData-and-bindings</id><content type="html" xml:base="https://alanquatermain.me/programming/swiftui/2019-11-15-CoreData-and-bindings/"><![CDATA[<p>If you’ve been playing with SwiftUI for a while, you’re likely familiar with the liberal use of <code class="language-plaintext highlighter-rouge">@State</code> and <code class="language-plaintext highlighter-rouge">@Binding</code> throughout the library. For instance, consider the following simple to-do item editor:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">enum</span> <span class="kt">Priority</span><span class="p">:</span> <span class="kt">Int</span><span class="p">,</span> <span class="kt">CaseIterable</span> <span class="p">{</span> 
    <span class="k">case</span> <span class="n">low</span><span class="p">,</span> <span class="n">normal</span><span class="p">,</span> <span class="n">high</span><span class="p">,</span> <span class="n">urgent</span>
    
    <span class="k">var</span> <span class="nv">title</span><span class="p">:</span> <span class="kt">LocalizedStringKey</span> <span class="p">{</span>
        <span class="k">switch</span> <span class="k">self</span> <span class="p">{</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">low</span><span class="p">:</span> <span class="k">return</span> <span class="s">"Low"</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">normal</span><span class="p">:</span> <span class="k">return</span> <span class="s">"Normal"</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">high</span><span class="p">:</span> <span class="k">return</span> <span class="s">"High"</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">urgent</span><span class="p">:</span> <span class="k">return</span> <span class="s">"Urgent"</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="kd">struct</span> <span class="kt">Item</span><span class="p">:</span> <span class="kt">Identifiable</span> <span class="p">{</span>
    <span class="k">var</span> <span class="nv">id</span><span class="p">:</span> <span class="kt">UUID</span>
    <span class="k">var</span> <span class="nv">title</span><span class="p">:</span> <span class="kt">String</span>
    <span class="k">var</span> <span class="nv">priority</span><span class="p">:</span> <span class="kt">Priority</span> <span class="o">=</span> <span class="o">.</span><span class="n">normal</span>
    <span class="k">var</span> <span class="nv">dueDate</span><span class="p">:</span> <span class="kt">Date</span> <span class="o">=</span> <span class="o">.</span><span class="n">distantPast</span>
    <span class="k">var</span> <span class="nv">notes</span><span class="p">:</span> <span class="kt">String</span> <span class="o">=</span> <span class="s">""</span>
<span class="p">}</span>

<span class="kd">struct</span> <span class="kt">Editor</span><span class="p">:</span> <span class="kt">View</span> <span class="p">{</span>
    <span class="kd">@State</span> <span class="k">var</span> <span class="nv">item</span><span class="p">:</span> <span class="kt">Item</span>
    
    <span class="k">var</span> <span class="nv">body</span><span class="p">:</span> <span class="kd">some</span> <span class="kt">View</span> <span class="p">{</span>
        <span class="kt">Form</span> <span class="p">{</span>
            <span class="kt">TextField</span><span class="p">(</span><span class="s">"Title"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="n">$item</span><span class="o">.</span><span class="n">title</span><span class="p">)</span>
            <span class="kt">Picker</span><span class="p">(</span><span class="s">"Priority"</span><span class="p">,</span> <span class="nv">selection</span><span class="p">:</span> <span class="n">$item</span><span class="o">.</span><span class="n">priority</span><span class="p">)</span> <span class="p">{</span>
                <span class="kt">ForEach</span><span class="p">(</span><span class="kt">Priority</span><span class="o">.</span><span class="n">allCases</span><span class="p">,</span> <span class="nv">id</span><span class="p">:</span> <span class="p">\</span><span class="o">.</span><span class="k">self</span><span class="p">)</span> <span class="p">{</span> <span class="n">priority</span> <span class="k">in</span>
                    <span class="kt">Text</span><span class="p">(</span><span class="n">priority</span><span class="o">.</span><span class="n">title</span><span class="p">)</span><span class="o">.</span><span class="nf">tag</span><span class="p">(</span><span class="n">priority</span><span class="p">)</span>
                <span class="p">}</span>
            <span class="p">}</span>
            <span class="kt">DatePicker</span><span class="p">(</span><span class="s">"Due Date"</span><span class="p">,</span> <span class="nv">selection</span><span class="p">:</span> <span class="n">$item</span><span class="o">.</span><span class="n">dueDate</span><span class="p">,</span>
                       <span class="nv">displayedComponents</span><span class="p">:</span> <span class="o">.</span><span class="n">date</span><span class="p">)</span>
            <span class="kt">TextField</span><span class="p">(</span><span class="s">"Notes"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="n">$item</span><span class="o">.</span><span class="n">notes</span><span class="p">)</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>There’s a single <code class="language-plaintext highlighter-rouge">@State</code> property containing a <code class="language-plaintext highlighter-rouge">struct</code> type, and this happily hands out the bindings required by <code class="language-plaintext highlighter-rouge">TextField</code>, <code class="language-plaintext highlighter-rouge">Picker</code>, and <code class="language-plaintext highlighter-rouge">DatePicker</code>. However, if the properties in the <code class="language-plaintext highlighter-rouge">Item</code> type were optional, the compiler wouldn’t be so happy:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">@State</span> <span class="k">var</span> <span class="nv">title</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span>
<span class="o">...</span>
<span class="c1">// Error: "Cannot convert value of type 'Binding&lt;String?&gt;' to expected</span>
<span class="c1">// argument type 'Binding&lt;String&gt;'"</span>
<span class="kt">TextField</span><span class="p">(</span><span class="s">"Title"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="n">$title</span><span class="p">)</span>
</code></pre></div></div>

<p>This is actually what you’ll find if you try to use a CoreData managed object type, because all its object-type properties are nullable:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="kt">Item</span><span class="p">:</span> <span class="kt">NSManagedObject</span> <span class="p">{</span>
    <span class="kd">@NSManaged</span> <span class="k">var</span> <span class="nv">title</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span>
    <span class="kd">@NSManaged</span> <span class="k">var</span> <span class="nv">priority</span><span class="p">:</span> <span class="kt">Int</span>
    <span class="kd">@NSManaged</span> <span class="k">var</span> <span class="nv">dueDate</span><span class="p">:</span> <span class="kt">Date</span><span class="p">?</span>
    <span class="kd">@NSManaged</span> <span class="k">var</span> <span class="nv">notes</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span>
    
    <span class="k">var</span> <span class="nv">priorityEnum</span><span class="p">:</span> <span class="kt">Priority</span> <span class="p">{</span>
        <span class="k">get</span> <span class="p">{</span> <span class="kt">Priority</span><span class="p">(</span><span class="nv">rawValue</span><span class="p">:</span> <span class="n">priority</span><span class="p">)</span> <span class="p">??</span> <span class="o">.</span><span class="n">normal</span> <span class="p">}</span>
        <span class="k">set</span> <span class="p">{</span> <span class="n">priority</span> <span class="o">=</span> <span class="n">newValue</span><span class="o">.</span><span class="n">rawValue</span> <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="kd">struct</span> <span class="kt">Editor</span><span class="p">:</span> <span class="kt">View</span> <span class="p">{</span>
    <span class="kd">@ObservedObject</span> <span class="k">var</span> <span class="nv">item</span><span class="p">:</span> <span class="kt">Item</span>
    
    <span class="k">var</span> <span class="nv">body</span><span class="p">:</span> <span class="kd">some</span> <span class="kt">View</span> <span class="p">{</span>
        <span class="kt">Form</span> <span class="p">{</span>
            <span class="c1">// Errors everywhere!</span>
            <span class="kt">TextField</span><span class="p">(</span><span class="s">"Title"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="n">$item</span><span class="o">.</span><span class="n">title</span><span class="p">)</span>
            <span class="kt">Picker</span><span class="p">(</span><span class="s">"Priority"</span><span class="p">,</span> <span class="nv">selection</span><span class="p">:</span> <span class="n">$item</span><span class="o">.</span><span class="n">priority</span><span class="p">)</span> <span class="p">{</span>
                <span class="kt">ForEach</span><span class="p">(</span><span class="kt">Priority</span><span class="o">.</span><span class="n">allCases</span><span class="p">,</span> <span class="nv">id</span><span class="p">:</span> <span class="p">\</span><span class="o">.</span><span class="k">self</span><span class="p">)</span> <span class="p">{</span> <span class="n">priority</span> <span class="k">in</span>
                    <span class="kt">Text</span><span class="p">(</span><span class="n">priority</span><span class="o">.</span><span class="n">title</span><span class="p">)</span><span class="o">.</span><span class="nf">tag</span><span class="p">(</span><span class="n">priority</span><span class="p">)</span>
                <span class="p">}</span>
            <span class="p">}</span>
            <span class="kt">DatePicker</span><span class="p">(</span><span class="s">"Due Date"</span><span class="p">,</span> <span class="nv">selection</span><span class="p">:</span> <span class="n">$item</span><span class="o">.</span><span class="n">dueDate</span><span class="p">,</span>
                       <span class="nv">displayedComponents</span><span class="p">:</span> <span class="o">.</span><span class="n">date</span><span class="p">)</span>
            <span class="kt">TextField</span><span class="p">(</span><span class="s">"Notes"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="n">$item</span><span class="o">.</span><span class="n">notes</span><span class="p">)</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h2 id="unwrapping-optional-bindings">Unwrapping optional bindings</h2>

<p>What are we to do with this? Well, there’s an initializer on <code class="language-plaintext highlighter-rouge">Binding</code> that looks like it’ll help—it takes a <code class="language-plaintext highlighter-rouge">Binding&lt;Optional&lt;Value&gt;&gt;</code> and returns a <code class="language-plaintext highlighter-rouge">Binding&lt;Value&gt;</code>.</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">/// Creates an instance by projecting the base optional value to its</span>
<span class="c1">/// unwrapped value, or returns `nil` if the base value is `nil`.</span>
<span class="kd">public</span> <span class="nf">init</span><span class="p">?(</span><span class="n">_</span> <span class="nv">base</span><span class="p">:</span> <span class="kt">Binding</span><span class="o">&lt;</span><span class="kt">Value</span><span class="p">?</span><span class="o">&gt;</span><span class="p">)</span>
</code></pre></div></div>

<p>Unfortunately, as the comment says, it only works if the value isn’t currently <code class="language-plaintext highlighter-rouge">nil</code>. So, you need to assign a default there first in order to use this. It’ll <em>work</em>, certainly, but quickly becomes awkward, not least because you probably want to use your binding within an <code class="language-plaintext highlighter-rouge">@ViewBuilder</code> block, and you can’t put general code in those—the compiler complains, because it needs every statement to evaluate with a return type expected by the <code class="language-plaintext highlighter-rouge">@ViewBuilder</code> in use.</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">@State</span> <span class="k">var</span> <span class="nv">title</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span> <span class="o">=</span> <span class="kc">nil</span>
<span class="k">var</span> <span class="nv">body</span><span class="p">:</span> <span class="kd">some</span> <span class="kt">View</span> <span class="p">{</span>
    <span class="kt">Form</span> <span class="p">{</span>
        <span class="k">if</span> <span class="n">title</span> <span class="o">==</span> <span class="kc">nil</span> <span class="p">{</span>
            <span class="c1">// Error: "'()' is not convertible to 'String?'"</span>
            <span class="n">title</span> <span class="o">=</span> <span class="s">""</span>
        <span class="p">}</span>
        <span class="kt">TextField</span><span class="p">(</span><span class="s">"Title"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="n">$title</span><span class="p">)</span><span class="o">!</span><span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Now, this works if you lift the setter up out of the <code class="language-plaintext highlighter-rouge">Form</code> block, but that becomes unwieldy with more than a couple of values:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">@State</span> <span class="k">var</span> <span class="nv">title</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span> <span class="o">=</span> <span class="kc">nil</span>
<span class="kd">@State</span> <span class="k">var</span> <span class="nv">notes</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span> <span class="o">=</span> <span class="kc">nil</span>
<span class="c1">// etc...</span>
<span class="k">var</span> <span class="nv">body</span><span class="p">:</span> <span class="kd">some</span> <span class="kt">View</span> <span class="p">{</span>
    <span class="k">if</span> <span class="n">title</span> <span class="o">==</span> <span class="kc">nil</span> <span class="p">{</span>
        <span class="n">title</span> <span class="o">=</span> <span class="s">""</span>
    <span class="p">}</span>
    <span class="k">if</span> <span class="n">notes</span> <span class="o">==</span> <span class="kc">nil</span> <span class="p">{</span>
        <span class="n">notes</span> <span class="o">=</span> <span class="s">""</span>
    <span class="p">}</span>
    <span class="c1">// etc...</span>
    <span class="kt">Form</span> <span class="p">{</span>
        <span class="kt">TextField</span><span class="p">(</span><span class="s">"Title"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="n">$title</span><span class="p">)</span><span class="o">!</span><span class="p">)</span>
        <span class="kt">TextField</span><span class="p">(</span><span class="s">"Notes"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="n">$notes</span><span class="p">)</span><span class="o">!</span><span class="p">)</span>
        <span class="c1">// etc...</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>You’re looking at a minimum four lines of code for each additional optional property. There’s a better way, though: you can add a new initializer to <code class="language-plaintext highlighter-rouge">Binding</code> that’s similar to the existing unwrapping one, but which takes a default value to assign first so it will guarantee a non-nil result:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">extension</span> <span class="kt">Binding</span> <span class="p">{</span>
    <span class="nf">init</span><span class="p">(</span><span class="n">_</span> <span class="nv">source</span><span class="p">:</span> <span class="kt">Binding</span><span class="o">&lt;</span><span class="kt">Value</span><span class="p">?</span><span class="o">&gt;</span><span class="p">,</span> <span class="n">_</span> <span class="n">defaultValue</span><span class="p">:</span> <span class="kt">Value</span><span class="p">)</span> <span class="p">{</span>
        <span class="c1">// Ensure a non-nil value in `source`.</span>
        <span class="k">if</span> <span class="n">source</span><span class="o">.</span><span class="n">wrappedValue</span> <span class="o">==</span> <span class="kc">nil</span> <span class="p">{</span>
            <span class="n">source</span><span class="o">.</span><span class="n">wrappedValue</span> <span class="o">=</span> <span class="n">defaultValue</span>
        <span class="p">}</span>
        <span class="c1">// Unsafe unwrap because *we* know it's non-nil now.</span>
        <span class="k">self</span><span class="o">.</span><span class="nf">init</span><span class="p">(</span><span class="n">source</span><span class="p">)</span><span class="o">!</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This initializer thus inlines the <code class="language-plaintext highlighter-rouge">if value == nil</code> rule above, leading to cleaner code and a one-line initialization:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">@State</span> <span class="k">var</span> <span class="nv">title</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span> <span class="o">=</span> <span class="kc">nil</span>
<span class="kd">@State</span> <span class="k">var</span> <span class="nv">notes</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span> <span class="o">=</span> <span class="kc">nil</span>
<span class="k">var</span> <span class="nv">body</span><span class="p">:</span> <span class="kd">some</span> <span class="kt">View</span> <span class="p">{</span>
    <span class="kt">Form</span> <span class="p">{</span>
        <span class="kt">TextField</span><span class="p">(</span><span class="s">"Title"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="n">$title</span><span class="p">,</span> <span class="s">""</span><span class="p">))</span>
        <span class="kt">TextField</span><span class="p">(</span><span class="s">"Notes"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="n">$notes</span><span class="p">,</span> <span class="s">""</span><span class="p">))</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h2 id="assigning-nil-or-non-nil-to-a-non-optional-binding">Assigning nil or non-nil to a non-optional binding</h2>

<p>A further situation occurs, though. What if nil is actually a reasonable value? Perhaps you would rather have a nil value than an empty string. Which of these looks better?</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="o">!</span><span class="n">item</span><span class="o">.</span><span class="n">title</span><span class="o">.</span><span class="n">isEmpty</span> <span class="p">{</span>
    <span class="c1">// use item.title</span>
<span class="p">}</span>

<span class="c1">// or</span>

<span class="k">if</span> <span class="k">let</span> <span class="nv">title</span> <span class="o">=</span> <span class="n">item</span><span class="o">.</span><span class="n">title</span> <span class="p">{</span>
    <span class="c1">// use title</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The answer is entirely subjective, of course, but <code class="language-plaintext highlighter-rouge">if let</code> is generally considered a “swifty” way to do things.</p>

<p>So, now you have a binding which will ensure nil is translated into an ‘empty’ value of some kind, but you’d really like to take any empty value and represent it as nil while still holding a <code class="language-plaintext highlighter-rouge">Binding&lt;Value&gt;</code> rather than <code class="language-plaintext highlighter-rouge">Binding&lt;Value?&gt;</code>. This, it turns out, is also possible thanks to the regular initializer for <code class="language-plaintext highlighter-rouge">Binding</code>, which uses closures to get and set the underlying value:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">/// Initializes from functions to read and write the value.</span>
<span class="kd">public</span> <span class="nf">init</span><span class="p">(</span><span class="nv">get</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">()</span> <span class="o">-&gt;</span> <span class="kt">Value</span><span class="p">,</span> <span class="nv">set</span><span class="p">:</span> <span class="kd">@escaping</span> <span class="p">(</span><span class="kt">Value</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Void</span><span class="p">)</span>
</code></pre></div></div>

<p>As long as the underlying <code class="language-plaintext highlighter-rouge">Value</code> is <code class="language-plaintext highlighter-rouge">Equatable</code>, it’s quite easy to use those to implement the replace-nil functionality we need:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">init</span><span class="p">(</span><span class="n">_</span> <span class="nv">source</span><span class="p">:</span> <span class="kt">Binding</span><span class="o">&lt;</span><span class="kt">Value</span><span class="p">?</span><span class="o">&gt;</span><span class="p">,</span> <span class="n">replacingNilWith</span> <span class="nv">nilValue</span><span class="p">:</span> <span class="kt">Value</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">self</span><span class="o">.</span><span class="nf">init</span><span class="p">(</span>
        <span class="nv">get</span><span class="p">:</span> <span class="p">{</span> <span class="n">source</span><span class="o">.</span><span class="n">wrappedValue</span> <span class="p">??</span> <span class="n">nilValue</span> <span class="p">},</span>
        <span class="nv">set</span><span class="p">:</span> <span class="p">{</span> <span class="n">newValue</span> <span class="k">in</span>
            <span class="k">if</span> <span class="n">newValue</span> <span class="o">==</span> <span class="n">nilValue</span> <span class="p">{</span>
                <span class="n">source</span><span class="o">.</span><span class="n">wrappedValue</span> <span class="o">=</span> <span class="kc">nil</span>
            <span class="p">}</span>
            <span class="k">else</span> <span class="p">{</span>
                <span class="n">source</span><span class="o">.</span><span class="n">wrappedValue</span> <span class="o">=</span> <span class="n">newValue</span>
            <span class="p">}</span>
    <span class="p">})</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Here the <code class="language-plaintext highlighter-rouge">source</code> binding is held by the two closures. The getter just uses the <code class="language-plaintext highlighter-rouge">??</code> operator to return the specified ‘nil value’ if necessary, and the setter explicitly checks if it’s been given that nil value, and transparently assigns nil to the <code class="language-plaintext highlighter-rouge">source</code> binding if so. This works well for CoreData types (avoid allocating byte storage if a ‘nil’ marker will do), and also for truly optional items. An example would be the ‘notes’ in our to-do item. A title is expected, but notes may be present on quite a small number of items, so this is what we’d use in that case:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">Form</span> <span class="p">{</span>
    <span class="c1">// Items should have titles, so use a 'default value' binding</span>
    <span class="kt">TextField</span><span class="p">(</span><span class="s">"Title"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="n">$item</span><span class="o">.</span><span class="n">title</span><span class="p">,</span> <span class="s">"New Item"</span><span class="p">))</span>
    
    <span class="c1">// Notes are entirely optional, so use a 'replace nil' binding</span>
    <span class="kt">TextField</span><span class="p">(</span><span class="s">"Notes"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="n">$item</span><span class="o">.</span><span class="n">notes</span><span class="p">,</span> <span class="nv">replacingNilWith</span><span class="p">:</span> <span class="s">""</span><span class="p">))</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Now your title will start out automatically with a value of <code class="language-plaintext highlighter-rouge">"New Item"</code>, and if everything is deleted from the notes field that property will be set to nil.</p>

<h2 id="binding-nilnon-nil-status-directly">Binding nil/non-nil status directly</h2>

<p>The ‘due date’ in our to-do item is another item which is legitimately nil when not used—not all to-do items have an explicit deadline—but there’s no reasonable ‘empty’ value for a date. We might use the epoch, or <code class="language-plaintext highlighter-rouge">Date.distantPast</code>, but the user has no easy way of inputting exactly that value to say “don’t use a date.” Instead you’d likely give your user a <code class="language-plaintext highlighter-rouge">Toggle</code> that turns the date on or off: when they turn it on, a default value is applied and a <code class="language-plaintext highlighter-rouge">Date Picker</code> created. Turning it off would take away the picker and set the value to nil.</p>

<p>This is also quite easy to assemble:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">init</span><span class="o">&lt;</span><span class="kt">T</span><span class="o">&gt;</span><span class="p">(</span><span class="n">isNotNil</span> <span class="nv">source</span><span class="p">:</span> <span class="kt">Binding</span><span class="o">&lt;</span><span class="kt">T</span><span class="p">?</span><span class="o">&gt;</span><span class="p">,</span> <span class="n">defaultValue</span><span class="p">:</span> <span class="kt">T</span><span class="p">)</span> <span class="k">where</span> <span class="kt">Value</span> <span class="o">==</span> <span class="kt">Bool</span> <span class="p">{</span>
    <span class="k">self</span><span class="o">.</span><span class="nf">init</span><span class="p">(</span><span class="nv">get</span><span class="p">:</span> <span class="p">{</span> <span class="n">source</span><span class="o">.</span><span class="n">wrappedValue</span> <span class="o">!=</span> <span class="kc">nil</span> <span class="p">},</span>
              <span class="nv">set</span><span class="p">:</span> <span class="p">{</span> <span class="n">source</span><span class="o">.</span><span class="n">wrappedValue</span> <span class="o">=</span> <span class="nv">$0</span> <span class="p">?</span> <span class="n">defaultValue</span> <span class="p">:</span> <span class="kc">nil</span> <span class="p">})</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This creates a <code class="language-plaintext highlighter-rouge">Binding&lt;Bool&gt;</code> from a <code class="language-plaintext highlighter-rouge">Binding&lt;T?&gt;</code> and a default value for <code class="language-plaintext highlighter-rouge">T</code>. The getter returns whether the <code class="language-plaintext highlighter-rouge">Binding&lt;T?&gt;</code> holds nil or not, and the setter assigns either nil or the supplied default value. This is quite simple to use, too:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">Toggle</span><span class="p">(</span><span class="s">"Has Due Date"</span><span class="p">,</span>
       <span class="nv">isOn</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="nv">isNotNil</span><span class="p">:</span> <span class="n">$item</span><span class="o">.</span><span class="n">dueDate</span><span class="p">,</span> <span class="n">defaultValue</span><span class="p">:</span> <span class="kt">Date</span><span class="p">()))</span>
<span class="k">if</span> <span class="n">item</span><span class="o">.</span><span class="n">dueDate</span> <span class="o">!=</span> <span class="kc">nil</span> <span class="p">{</span>
    <span class="kt">DatePicker</span><span class="p">(</span><span class="kt">DatePicker</span><span class="p">(</span><span class="s">"Due Date"</span><span class="p">,</span> <span class="nv">selection</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="n">$item</span><span class="o">.</span><span class="n">dueDate</span><span class="p">)</span><span class="o">!</span><span class="p">,</span>
                       <span class="nv">displayedComponents</span><span class="p">:</span> <span class="o">.</span><span class="n">date</span><span class="p">))</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Here you’ve used the <code class="language-plaintext highlighter-rouge">Binding(isNotNil:defaultValue:)</code> for the <code class="language-plaintext highlighter-rouge">Toggle</code>, and a regular unwrapping binding for the <code class="language-plaintext highlighter-rouge">DatePicker</code>.</p>

<h2 id="all-together-now">All together now…</h2>

<p>This leads to a CoreData-backed form binding to optional properties that looks almost as concise as the pure <code class="language-plaintext highlighter-rouge">struct</code> format:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">enum</span> <span class="kt">Priority</span><span class="p">:</span> <span class="kt">Int</span><span class="p">,</span> <span class="kt">CaseIterable</span> <span class="p">{</span> 
    <span class="k">case</span> <span class="n">low</span><span class="p">,</span> <span class="n">normal</span><span class="p">,</span> <span class="n">high</span><span class="p">,</span> <span class="n">urgent</span>
    
    <span class="k">var</span> <span class="nv">title</span><span class="p">:</span> <span class="kt">LocalizedStringKey</span> <span class="p">{</span>
        <span class="k">switch</span> <span class="k">self</span> <span class="p">{</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">low</span><span class="p">:</span> <span class="k">return</span> <span class="s">"Low"</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">normal</span><span class="p">:</span> <span class="k">return</span> <span class="s">"Normal"</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">high</span><span class="p">:</span> <span class="k">return</span> <span class="s">"High"</span>
        <span class="k">case</span> <span class="o">.</span><span class="nv">urgent</span><span class="p">:</span> <span class="k">return</span> <span class="s">"Urgent"</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="kd">class</span> <span class="kt">Item</span><span class="p">:</span> <span class="kt">NSManagedObject</span> <span class="p">{</span>
    <span class="kd">@NSManaged</span> <span class="k">var</span> <span class="nv">title</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span>
    <span class="kd">@NSManaged</span> <span class="k">var</span> <span class="nv">priority</span><span class="p">:</span> <span class="kt">Int</span>
    <span class="kd">@NSManaged</span> <span class="k">var</span> <span class="nv">dueDate</span><span class="p">:</span> <span class="kt">Date</span><span class="p">?</span>
    <span class="kd">@NSManaged</span> <span class="k">var</span> <span class="nv">notes</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span>
    
    <span class="k">var</span> <span class="nv">priorityEnum</span><span class="p">:</span> <span class="kt">Priority</span> <span class="p">{</span>
        <span class="k">get</span> <span class="p">{</span> <span class="kt">Priority</span><span class="p">(</span><span class="nv">rawValue</span><span class="p">:</span> <span class="n">priority</span><span class="p">)</span> <span class="p">??</span> <span class="o">.</span><span class="n">normal</span> <span class="p">}</span>
        <span class="k">set</span> <span class="p">{</span> <span class="n">priority</span> <span class="o">=</span> <span class="n">newValue</span><span class="o">.</span><span class="n">rawValue</span> <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="kd">struct</span> <span class="kt">Editor</span><span class="p">:</span> <span class="kt">View</span> <span class="p">{</span>
    <span class="kd">@ObservedObject</span> <span class="k">var</span> <span class="nv">item</span><span class="p">:</span> <span class="kt">Item</span>
    
    <span class="k">var</span> <span class="nv">body</span><span class="p">:</span> <span class="kd">some</span> <span class="kt">View</span> <span class="p">{</span>
        <span class="kt">Form</span> <span class="p">{</span>
            <span class="kt">TextField</span><span class="p">(</span><span class="s">"Title"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="n">$item</span><span class="o">.</span><span class="n">title</span><span class="p">,</span> <span class="s">"New Item"</span><span class="p">))</span>
            
            <span class="kt">Picker</span><span class="p">(</span><span class="s">"Priority"</span><span class="p">,</span> <span class="nv">selection</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="n">$item</span><span class="o">.</span><span class="n">priority</span><span class="p">,</span> <span class="o">.</span><span class="n">normal</span><span class="p">))</span> <span class="p">{</span>
                <span class="kt">ForEach</span><span class="p">(</span><span class="kt">Priority</span><span class="o">.</span><span class="n">allCases</span><span class="p">,</span> <span class="nv">id</span><span class="p">:</span> <span class="p">\</span><span class="o">.</span><span class="k">self</span><span class="p">)</span> <span class="p">{</span> <span class="n">priority</span> <span class="k">in</span>
                    <span class="kt">Text</span><span class="p">(</span><span class="n">priority</span><span class="o">.</span><span class="n">title</span><span class="p">)</span><span class="o">.</span><span class="nf">tag</span><span class="p">(</span><span class="n">priority</span><span class="p">)</span>
                <span class="p">}</span>
            <span class="p">}</span>
            
            <span class="kt">Toggle</span><span class="p">(</span><span class="s">"Has Due Date"</span><span class="p">,</span> <span class="nv">isOn</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="nv">isNotNil</span><span class="p">:</span> <span class="n">$item</span><span class="o">.</span><span class="n">dueDate</span><span class="p">,</span> 
                                                 <span class="n">defaultValue</span><span class="p">:</span> <span class="kt">Date</span><span class="p">()))</span>
            <span class="k">if</span> <span class="n">item</span><span class="o">.</span><span class="n">date</span> <span class="o">!=</span> <span class="kc">nil</span> <span class="p">{</span>
                <span class="kt">DatePicker</span><span class="p">(</span><span class="s">"Due Date"</span><span class="p">,</span> <span class="nv">selection</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="n">$item</span><span class="o">.</span><span class="n">dueDate</span><span class="o">!</span><span class="p">),</span>
                           <span class="nv">displayedComponents</span><span class="p">:</span> <span class="o">.</span><span class="n">date</span><span class="p">)</span>
            <span class="p">}</span>
            
            <span class="kt">TextField</span><span class="p">(</span><span class="s">"Notes"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="n">$item</span><span class="o">.</span><span class="n">notes</span><span class="p">,</span> <span class="nv">replacingNilWith</span><span class="p">:</span> <span class="s">""</span><span class="p">))</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="available-now">Available Now!</h3>

<p>These extensions to <code class="language-plaintext highlighter-rouge">Binding</code> are <a href="https://github.com/AlanQuatermain/AQUI">available now</a> via the Swift Package Manager. It uses Swift v5.1 and tags its contents with the appropriate availability modifiers for macOS, iOS, tvOS, and watchOS. Including it is simple:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="nv">package</span> <span class="o">=</span> <span class="kt">Package</span><span class="p">(</span>
    <span class="o">...</span>
    <span class="nv">dependencies</span><span class="p">:</span> <span class="p">[</span>
        <span class="o">...</span>
        <span class="o">.</span><span class="nf">package</span><span class="p">(</span><span class="nv">url</span><span class="p">:</span> <span class="s">"https://github.com/AlanQuatermain/AQUI.git"</span><span class="p">,</span> <span class="nv">from</span><span class="p">:</span> <span class="s">"0.1.0"</span><span class="p">)</span>
    <span class="p">],</span>
    <span class="nv">swiftLanguageVersions</span><span class="p">:</span> <span class="p">[</span>
        <span class="o">...</span>
        <span class="o">.</span><span class="nf">version</span><span class="p">(</span><span class="s">"5.1"</span><span class="p">)</span>
    <span class="p">]</span>
<span class="p">)</span>
</code></pre></div></div>

<p>Using it in code is straightforward too:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">import</span> <span class="kt">SwiftUI</span>
<span class="kd">import</span> <span class="kt">AQUI</span>

<span class="o">...</span>
    <span class="kt">TextField</span><span class="p">(</span><span class="s">"Notes"</span><span class="p">,</span> <span class="nv">text</span><span class="p">:</span> <span class="kt">Binding</span><span class="p">(</span><span class="n">$cdObject</span><span class="o">.</span><span class="n">notes</span><span class="p">,</span> <span class="nv">replacingNilWith</span><span class="p">:</span> <span class="s">""</span><span class="p">))</span>
<span class="o">...</span>
</code></pre></div></div>]]></content><author><name>Jim Dovey</name><email>jimdovey@mac.com</email></author><category term="programming" /><category term="swiftui" /><category term="swift" /><category term="ios" /><category term="apple" /><summary type="html"><![CDATA[If you’ve been playing with SwiftUI for a while, you’re likely familiar with the liberal use of @State and @Binding throughout the library. For instance, consider the following simple to-do item editor:]]></summary></entry><entry><title type="html">SwiftUI: A Story</title><link href="https://alanquatermain.me/programming/swiftui/2019-08-30-swiftui-a-story/" rel="alternate" type="text/html" title="SwiftUI: A Story" /><published>2019-08-30T00:00:00-07:00</published><updated>2019-08-30T00:00:00-07:00</updated><id>https://alanquatermain.me/programming/swiftui/swiftui-a-story</id><content type="html" xml:base="https://alanquatermain.me/programming/swiftui/2019-08-30-swiftui-a-story/"><![CDATA[<p>I’m back, folks, and I’m working on a book about <a href="https://developer.apple.com/xcode/swiftui">SwiftUI</a>.</p>

<p>“Now?” you ask. “There are already <a href="https://swiftui-lab.com">plenty</a> of <a href="https://www.hackingwithswift.com/quick-start/swiftui">people</a> already <a href="https://store.raywenderlich.com/products/swiftui-by-tutorials">writing</a> about it. Aren’t you a little late? Are you just jumping on the bandwagon?”</p>

<p>Well, no. Well, maybe. But not <em>so</em> much. I can’t really say I’m <em>late</em> exactly. Let me tell you about a little meeting I attended in 2015, about a year after I joined Apple.</p>

<p>It was a big conference room, seating about 25–30 people or thereabouts. There were two giant screens at one end, on which were displayed a Keynote presentation and the contents of the presenter’s Xcode window. There were some heavyweights from the UIKit and WatchKit teams there. A couple of unit directors from watchOS, people involved in the watchOS-specific UI frameworks. Some people who were really excited about Swift.</p>

<p>Jerry Garcia. Jimi Hendrix.</p>

<p><a href="https://en.wikipedia.org/wiki/The_Intro_and_the_Outro">Adolf Hitler on vibes</a>.</p>

<p>Quite an audience, and quite a show. A couple of rather clever chaps, Jacob Xiao and Kyle Macomber, were showing us a new UI framework they’d devised, and were proposing as the official way to write watchOS apps that ran on-device—a replacement for WatchKit, which at that time ran all code on the companion iPhone. Their approach was to make use of immutable value types to represent views and their state, with all of the benefits that brought to an increasingly multi-threaded and parallel world. In fact, Jacob and WatchKit engineer Alex Migicovsky presented on this very topic at WWDC in 2016: <a href="https://developer.apple.com/videos/play/wwdc2016/419/">Protocol and Value Oriented Programming in UIKit</a>. This talk describes quite well the aims of this new framework, which would be announced to the public three years later under the name of <strong>SwiftUI</strong>.</p>

<p>Things changed in the years since I last looked at the project (some time in 2017 I believe), and the various features added in Swift 5.1 to create the declarative UI DSL weren’t even being talked about (at least, not where I could hear them). The SwiftUI framework that is being released this fall with macOS 10.15 and iOS 13 is a markedly different beast.</p>

<p>One thing I remember being tackled a lot was the problem of relating a SwiftUI <code class="language-plaintext highlighter-rouge">View</code> struct to the underlying <code class="language-plaintext highlighter-rouge">CALayer</code> or similar, so we might insert and remove views from the hierarchy and have the right animations occur. For instance, going from two text fields to three by insertion: <code class="language-plaintext highlighter-rouge">"red" | "blue"</code> to <code class="language-plaintext highlighter-rouge">"red" | "green" | "blue"</code>. Does the content “blue” change to “green” and a new “blue” appear? Or does the existing “blue” move out of the way to allow “green” to appear? What if we insert “green” while changing “blue” to “mauve”? Just think about how you’d tie these things together properly, and then how you’d do so with the absolute minimum of burden on the user.</p>

<p>It was a seriously hard problem, and they nailed it—there’s no need to attach identifiers to view structures in SwiftUI. The framework is able to figure it all out on its own. We now have view preferences (see Javier Nigro’s excellent <a href="https://swiftui-lab.com/communicating-with-the-view-tree-part-1/">three-part series</a>), <code class="language-plaintext highlighter-rouge">@Environment</code>, we have <code class="language-plaintext highlighter-rouge">@State</code> and <code class="language-plaintext highlighter-rouge">@Binding</code>, and we have the Combine framework and all that entails. So much of the work that went into SwiftUI was focussed on reducing the visual complexity of all these common tasks, and they’ve succeeded admirably.</p>

<p>I’ve been waiting with bated breath for several years now to see this project unveiled, and now it’s here I’m excited to see what we can do with it, and how it’ll shape UI APIs on Apple platforms in the years to come.</p>]]></content><author><name>Jim Dovey</name><email>jimdovey@mac.com</email></author><category term="programming" /><category term="swiftui" /><category term="swift" /><category term="ios" /><category term="apple" /><summary type="html"><![CDATA[I’m back, folks, and I’m working on a book about SwiftUI.]]></summary></entry><entry><title type="html">Adobe Joins the Readium Foundation</title><link href="https://alanquatermain.me/technology/epublishing/2013-09-09-adobe-joins-the-readium-foundation/" rel="alternate" type="text/html" title="Adobe Joins the Readium Foundation" /><published>2013-09-09T10:18:00-07:00</published><updated>2013-09-09T10:18:00-07:00</updated><id>https://alanquatermain.me/technology/epublishing/adobe-joins-the-readium-foundation</id><content type="html" xml:base="https://alanquatermain.me/technology/epublishing/2013-09-09-adobe-joins-the-readium-foundation/"><![CDATA[<p>I’m feeling rather legitimized today: none other than <a href="http://www.adobe.com/">Adobe</a> themselves have joined the <a href="http://readium.org/">Readium Foundation</a>. The initial goal of our collaboration is to ensure that any reading system built using the <a href="http://readium/org/projects/readium-sdk">Readium SDK</a> will have the option to include built-in handling for EPUB 2 and EPUB 3 documents protected using <a href="http://www.adobe.com/products/content-server.html">Adobe Content Server 4</a> – the most pervasive form of DRM in the eBook industry.</p>

<p>Now, you all know that I’m personally not convinced of the need for DRM, but even I have to admit that this particular effort will be incredibly useful: the vast majority of eBook publishers and vendors in the world make use of Adobe Content Server and its DRM. So long as that’s the case, any new eReader technology will have a difficult road ahead if it cannot work with those existing tools and ecosystem. Maybe we can wean everyone from DRM in the long term, but we need to get them in the door first, and this is how it happens.</p>

<p>So, we now have Kobo, Sony, and Adobe involved. Two more ‘A’s are left in the wings– I wonder if or when either of those will decide to join in?</p>

<p>You can <a href="http://readium.org/news/adobe-joins-readium-foundation">view the official announcement here</a>.</p>]]></content><author><name>Jim Dovey</name><email>jimdovey@mac.com</email></author><category term="technology" /><category term="epublishing" /><category term="epub3" /><category term="adobe" /><summary type="html"><![CDATA[I’m feeling rather legitimized today: none other than Adobe themselves have joined the Readium Foundation. The initial goal of our collaboration is to ensure that any reading system built using the Readium SDK will have the option to include built-in handling for EPUB 2 and EPUB 3 documents protected using Adobe Content Server 4 – the most pervasive form of DRM in the eBook industry.]]></summary></entry><entry><title type="html">iTunes Radio</title><link href="https://alanquatermain.me/technology/2013-06-18-itunes-radio/" rel="alternate" type="text/html" title="iTunes Radio" /><published>2013-06-18T15:56:00-07:00</published><updated>2013-06-18T15:56:00-07:00</updated><id>https://alanquatermain.me/technology/itunes-radio</id><content type="html" xml:base="https://alanquatermain.me/technology/2013-06-18-itunes-radio/"><![CDATA[<p>From <a href="http://daringfireball.net/linked/2013/06/18/itunes-radio">John Gruber</a></p>
<blockquote>
  <p>Tyler Hayes on iTunes Radio:</p>

  <blockquote>
    <p>The design and goal is clearly focused on listeners purchasing music — but even so, iTunes Radio feels like the first truly modern take on what terrestrial radio wishes it could be. Radio was always meant to be a promotion tool, a way to sell more music, but without being built directly on top of the world’s biggest music retailer, it was always too distant from the marketplace to be more effectual. Now a “buy” button lives next to every song, or a wish list one for those hesitant, and it feels like this is how modern radio should function.</p>
  </blockquote>

  <p>Agreed; iTunes Radio is well-done and well-designed. I’m a little surprised Apple is making everyone wait for iOS 7 to get it.</p>
</blockquote>

<p>I, on the other hand, am absolutely <em>not</em> surprised that Big Media is refusing to allow this product to operate in more than one market.</p>

<p>Once again they’ll need to be dragged, kicking and screaming, into a worldwide rollout. Once again this will not be possible until the absolute <em>maximum</em> amount of positive evidence has been provided by Apple.</p>

<p>And once again they’ll doubtless choose to keep Canada out of the deal for as long as possible so it can act as a proxy for ‘what the US market would be like’ to gainsay any evidence.</p>]]></content><author><name>Jim Dovey</name><email>jimdovey@mac.com</email></author><category term="technology" /><summary type="html"><![CDATA[From John Gruber Tyler Hayes on iTunes Radio: The design and goal is clearly focused on listeners purchasing music — but even so, iTunes Radio feels like the first truly modern take on what terrestrial radio wishes it could be. Radio was always meant to be a promotion tool, a way to sell more music, but without being built directly on top of the world’s biggest music retailer, it was always too distant from the marketplace to be more effectual. Now a “buy” button lives next to every song, or a wish list one for those hesitant, and it feels like this is how modern radio should function. Agreed; iTunes Radio is well-done and well-designed. I’m a little surprised Apple is making everyone wait for iOS 7 to get it.]]></summary></entry></feed>