<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>kelan.io</title><description>All recent posts on kelan.io</description><link>https://kelan.io/</link><language>en-us</language><copyright>Copyright (c) 2010 - 2026 Kelan Champagne</copyright><pubDate>Sun, 15 Feb 2026 22:13:49 GMT</pubDate><ttl>1800</ttl><atom:link href="https://kelan.io/feeds/all-posts.xml" rel="self" type="application/rss+xml"/><item><title>Not Today, Rivers</title><link>https://kelan.io/2026/not-today-rivers/</link><guid isPermaLink="true">https://kelan.io/2026/not-today-rivers/</guid><description>&lt;GalleryImage
  src=&quot;/2026/not-today-rivers/hurley.png&quot;
  thumbSrc=&quot;/2026/not-today-rivers/hurley_thumb.png&quot;
  caption=&quot;This song just came on my “Made For You” station&quot;
/&gt;</description><pubDate>Sun, 15 Feb 2026 00:00:00 GMT</pubDate></item><item><title>Ticket Party 🎉</title><link>https://kelan.io/2026/ticket-party/</link><guid isPermaLink="true">https://kelan.io/2026/ticket-party/</guid><description>I&apos;ve been using the [Codex app](https://openai.com/codex/) a lot since it came out (which was what, not even 2 weeks ago? Things are moving _fast_). It&apos;s a really nice app. I had been using Claude Code a bunch, and enjoying the results, but I never loved the terminal interface (TUI) app. I know it&apos;s [technically impressive how they do it](https://x.com/trq212/status/2014051501786931427), but I&apos;m sitting here using a Mac, with a GUI and buttons and scrollable things… Let&apos;s use &apos;em!

So, Codex.app is a nice UI improvement[^model-comparison]. But now that I&apos;m using it more heavily, I&apos;m quickly getting overwhelmed with all the tasks it&apos;s showing me.

[^model-comparison]: And I haven&apos;t noticed any difference (better or worse) in the quality of the model results between ClaudeCode and Codex. I haven&apos;t done any exhaustive comparisons, but the current generation models all seem plenty capable for what I&apos;m asking them to do. And it&apos;s really a huge leap forward from even a few months ago.

&lt;GalleryImage src=&quot;/2026/ticket-party/codex.png&quot; styleVariant=&quot;center&quot; caption=&quot;Codex App in action. But wait, what was I doing? And what did I want to do next??&quot; /&gt;

The app&apos;s UI model is simple enough: add projects to the sidebar, and then in each project, you can start multiple chats. It&apos;s great for having parallel conversations. But since the responses (and coding and testing) in each one can be a little slow, **I was often waiting for one thing to finish before I could start the next**.

I could probably use worktrees to avoid some of the blocking. But that doesn&apos;t actually help all that much with a Mac or iOS app, where you don&apos;t want to be running too many copies of the app in parallel. It&apos;s easier to develop/test a single change at a time.

So I found myself starting one conversation in Codex, then while it&apos;s working, start planning the next (and having it write a `something-plan.md` file to my `docs/` dir), but then waiting to implement that plan until the previous conversation was done. But then the order of chats in the sidebar would shift, and I&apos;d forget which one was next, and which plan docs were ready or done or not, and I&apos;d end up feeling overloaded.

Furthermore, when I&apos;d come back to the project later, I&apos;d have forgotten what I was working on, what order of things should go next, etc. So I wanted a little task-tracking tool to help myself and the agent.

I had thought that [beads](https://github.com/steveyegge/beads) was maybe supposed to help with this (e.g. by letting me add a bunch of TODO tasks), but I never quite understood how it worked. And the more I read, the more it seemed like it didn&apos;t actually work that way.

So, I figured I&apos;d just make my own task tracker[^task-tracker]. Meanwhile, I saw [this similar idea from Daniel Duan first](https://hachyderm.io/@dduan@mastodon.social/116039123027386744), which reinforced that there was something useful in this idea. So I set off to build my own, and lucky for me, I had an eager LLM ready to help.

[^task-tracker]: Said every software developer ever, at least once in their career. I mean, how hard could it be?

So Tuesday morning I started a new project in Xcode, added the dir to Codex, and started describing my idea. That night, it was working well enough to be adding features to itself. And now two days later, I think it&apos;s interesting enough to share. It&apos;s nowhere near done, or even MVP, but I wanted to share an early glimpse of it, to see if it resonates with anyone else.

## The Basic Idea

&lt;GalleryImage src=&quot;/2026/ticket-party/ticket-party.png&quot; styleVariant=&quot;center&quot; caption=&quot;TicketParty App, working on self-improvement.&quot; /&gt;

Instead of starting a chat and then going synchronously back-and-forth with the agent, I wanted to queue up a bunch of &quot;tickets&quot; for it to do. When it&apos;s done with one, it should move on to the next. That takes my sometimes-slow responsiveness out of the loop. But it also lets me refine the backlog while the agent is working (i.e., taking advantage of the agent&apos;s sometimes-slow responsiveness).

And yes, I said &quot;backlog&quot;. No, I&apos;m not at all a Professional Scrum Person. But yes, I sorta did build myself a bug tracker. I suppose everyone does it at some point. And at least I did it quickly.

So, as I&apos;m working, I just add tickets for things I think I want it to do next, as the ideas strike me. Then I manually sort them in the backlog, add more notes, and (as of late last night) can have concurrent &quot;planning&quot; discussions in a chat interface on each ticket. Then when I&apos;m happy with the plan, I can mark it as `Ready for Implementation`, and it will get processed in the queue when the agent gets to it.

## Current Status

- The name is terrible (I have been trying hard to not get hung up on little details such as the name — it&apos;s actually easier to do that when I can so quickly make progress on features, so that&apos;s fun)
- The UI is rough, but fairly functional
- The &quot;Run Loop&quot; part doesn&apos;t fully work yet — but it&apos;s close
    - You can manually approximate it, by just clicking &quot;Start&quot; on the next ticket in the backlog
- The code probably needs a lot of refactoring
    - In fact, this has been a fun experiment to learn how good the coding agents are these days (quite good, actually!)
    - I know there are things that aren&apos;t ideal
    - But I also feel confident that I can do large refactorings as necessary; the agents are actually quite good at that. So, again, I&apos;m not worried about class/function names, because I know I can correct those later, as I get a better understanding of how the whole thing should work.
- But, it&apos;s mostly &quot;self-hosting&quot; at this point. I&apos;m writing most of the new features in TicketParty by using TicketParty. Yay! 🎉

## Future Ideas

There are a ton of obvious next steps (big and small), but the areas I&apos;m most excited about are:
- When the backlog has more refined details in it, then I can queue up a bunch of tickets, start the &quot;run loop&quot;, and just sit back and watch the changes roll in.
- If the agent has questions, it should queue them up for me. This can go both ways!
- When I return to my computer, I should get a dashboard with the list of changes that are done, some ways for me to review them and comment on them, and see a list of questions for me (and a way for me to quickly give answers)

## At a Higher Level

I think the interesting thing is that I could build this tool for myself in just a few days. It would have taken me weeks before, so I&apos;d just never have done it. Maybe a more clever engineer than me would have figured out how to simplify it in a way that was more feasible to build (like, just a text file with tasks, and then a bash loop iterating over that). But I love that now I can have it both ways — I can quickly build a tool, which is nicer than it has any right to be.

You can tell by the name, the crude UI, and the lack of polish that I&apos;m not slowing down to make too many careful decisions. But I&apos;ve come to realize that&apos;s actually another powerful thing about LLM-assisted development: I know I can ask the agent to update/refactor something later, so I don&apos;t slow down to overthink it up front. And in hindsight, I think that&apos;s a thing that really slowed me down as an engineer in the past. So I&apos;m going faster now not just because I have an LLM writing code, but because it&apos;s helping me jump right over all the mental hurdles that used to trip me up in the past.

As an aside, I know there is a lot of buzz around [OpenClaw](https://openclaw.ai/) right now, but frankly I feel a little skeptical about it. I don&apos;t yet trust these agents that much, to give them that much autonomy. And also, I _like_ thinking through the details of my projects. So, I think TicketParty is a meaningfully different approach; **instead of asking the agent to &quot;do everything&quot; for me, I get to micromanage it to do the tasks that I want**. And this tool just lets me do that in a convenient way. But, admittedly, I haven&apos;t used OpenClaw, so please LMK if I&apos;m misunderstanding or re-inventing a wheel here.</description><pubDate>Thu, 12 Feb 2026 00:00:00 GMT</pubDate></item><item><title>Voids</title><link>https://kelan.io/2017/voids/</link><guid isPermaLink="true">https://kelan.io/2017/voids/</guid><description>I recently ran into a problem where I was confused by the difference between
`()` and `Void` in Swift.

**TL;DR** `Void` is a type, but not a value, and `()` is both a type and
a value.

## Sometimes they&apos;re the same

My confusion arose from the fact that I think of them as interchangeable, when it comes to
function signatures.  For example, these two are the same:

```swift
func asyncWork1(completion: @escaping (String) -&gt; Void)
func asyncWork2(completion: @escaping (String) -&gt; ())
```

## But not always

However, given this generic `enum` definition[^1]:

```swift
enum Result&lt;T&gt; {
    case success(T)
    case failure(Error)
}
```

[^1]: The fact that it&apos;s a `Result` isn&apos;t important, but just is the real example of where this came up for me.

I was trying to represent the `success` case, but without a value.  So I tried
this:

```swift
let result1: Result&lt;Void&gt; = .success(Void)
```

But that gave this (somewhat cryptic) error:

```
error: member &apos;success&apos; in &apos;Result&lt;Void&gt;&apos; (aka &apos;Result&lt;()&gt;&apos;) produces result of type &apos;Result&lt;T&gt;&apos;, but context expects &apos;Result&lt;Void&gt;&apos; (aka &apos;Result&lt;()&gt;&apos;)
```

It&apos;s because `Void` is just a type, not a value, and the compiler is expecting a
value here.

So, to fix it, we use `()` instead, which is a value.

```swift
let result2: Result&lt;Void&gt; = .success(())
```

And, since we&apos;ve realized that the issue is `Void` is a type, not a value, it
seems obvious to try this, which also works (but does feel a bit odd to me
[^odd]):

[^odd]: And not just because it&apos;s literally just adding 4 extra, unnecessary characters.

```swift
let result3: Result&lt;Void&gt; = .success(Void())
```

## Parting Thoughts

I do wonder a bit about why `()` is allowed as a type as well as a value
[^constructing-nothing].  I think it has to do with the subtle details of
Swift&apos;s syntax, and tuples, and the desire to be able to write `() -&gt; ()` as a
function signature, instead of `Void -&gt; Void`?  But, it did lead to some
confusion in this case (no pun intended).

[^constructing-nothing]: The `Void()` solution briefly made me think it would be funny to try to explain this by saying &quot;the empty parens `()` are used for calling the constructor of the type next to it, and since there is *nothing* next to it, it constructs a `Void`&quot;.  But that&apos;s almost *too* plausible.  🙃


---

*Thanks, as usual, to [Jacob](https://twitter.com/jtbandes) for pointing out the
type/value difference to me here.*</description><pubDate>Fri, 28 Apr 2017 00:00:00 GMT</pubDate></item><item><title>Slack Abbrevs</title><link>https://kelan.io/2016/slack-abbrevs/</link><guid isPermaLink="true">https://kelan.io/2016/slack-abbrevs/</guid><description>Based on actual experience this week, the risk of confusion between these two
different private channels (with the same Becky, but two differnet Jameses) is
not just theoretical.


&lt;GalleryImage src=&quot;/2016/slack-abbrevs/slack-abbrevs.png&quot; thumbSrc=&quot;/2016/slack-abbrevs/slack-abbrevs.png&quot; width={438} height={126} caption={&quot;Thankfully, nothing actually\nsensitive was said into the wrong one, but it&apos;s still very helpful labelling.&quot;} /&gt;

I was especially befuddled by the fact that Slack added the last initial to
Becky (which didn&apos;t need it -- because it&apos;s the same Becky), but not to James
(which did need it).  But then I learned that Becky manually edited her first
name in Slack to include her last initial, to avoid this type of confusion.
What a twist ending!</description><pubDate>Sat, 10 Dec 2016 00:00:00 GMT</pubDate></item><item><title>The answer is 4 nails</title><link>https://kelan.io/2016/the-answer-is-4-nails/</link><guid isPermaLink="true">https://kelan.io/2016/the-answer-is-4-nails/</guid><description>The other day I was wondering about the origin of the name of the band Nine
Inch Nails.  So I thought I&apos;d ask Siri…

&lt;GalleryImage src=&quot;/2016/the-answer-is-4-nails/4-nails.png&quot; thumbSrc=&quot;/2016/the-answer-is-4-nails/4-nails.png&quot; width={750} height={1334} caption={&quot;Of course it is.  I feel silly for even asking.&quot;} /&gt;

Everybody knows the old rule of thumb: Two inches per nail, you can&apos;t fail.
(Except if you then try to convert to nails again.)</description><pubDate>Sat, 10 Dec 2016 00:00:00 GMT</pubDate></item><item><title>TableFlip Registration</title><link>https://kelan.io/2016/tableflip-registration/</link><guid isPermaLink="true">https://kelan.io/2016/tableflip-registration/</guid><description>I&apos;ve been beta testing [TableFlip](http://tableflipapp.com), which is a nice macOS app for editing
Markdown tables.  It was just [released today](http://christiantietze.de/posts/2016/10/tableflip-launch/),
so check it out!  (And, if you want a discount, check out the [share for
discount](http://tableflipapp.com/share-for-discount/) promotion.)

I really like this touch when entering your registration code:

&lt;GalleryImage src=&quot;/2016/tableflip-registration/TableFlip-registration.gif&quot; thumbSrc=&quot;/2016/tableflip-registration/TableFlip-registration.gif&quot; width={1166} height={744} caption={&quot;Making it rain (smileys). \ud83c\udf89&quot;} /&gt;</description><pubDate>Wed, 05 Oct 2016 00:00:00 GMT</pubDate></item><item><title>Promise Lifetime Question</title><link>https://kelan.io/2016/promise-lifetime-question/</link><guid isPermaLink="true">https://kelan.io/2016/promise-lifetime-question/</guid><description>I&apos;m starting to explore using Promises more in Swift, especially after reading Soroush Khanlou&apos;s
[posts](http://khanlou.com/2016/08/promises-in-swift/)
[about](http://khanlou.com/2016/08/common-patterns-with-promises/) them.  I like the idea a lot, but
I have some questions about best practices for managing the lifetimes of related objects (for
specific use-cases).


## Motivating Example

I&apos;m trying to wrap some preexisting Cocoa API that uses the delegate pattern for callbacks, and
making an API that returns a `Promise`.

Let’s say you have this API that uses a delegate for callback from some async operation:

```swift
protocol ExampleAPIDelegate: NSObjectProtocol {
    func workCompleted(result: String)
}

class ExampleAPI {
    static var sharedInstance: ExampleAPI

    weak var delegate: ExampleAPIDelegate?

    /// The result of this async work comes via the delegate callback.
    func startWork() { … }
}
```


Here&apos;s how you might &quot;wrap&quot; it, so that you can deal with it by using a `Promise` instead:

```swift
/// The enum is just for namespacing
enum ExampleWrapper {

    /// Private helper to serve as the delegate
    private class DelegateShim: ExampleAPIDelegate {
        let fulfill: (String) -&gt; Void
        let reject: (Error) -&gt; Void

        init (fulfill: @escaping (String) -&gt; Void, reject: @escaping (Error) -&gt; Void) {
            self.fulfill = fulfill
            self.reject = reject
        }

        func workCompleted(result: String) {
            fulfill(result)
        }
    }

    static func promisedWorkResult() -&gt; Promise&lt;String&gt; {
        return Promise(work: { (fulfill, reject) in
            let shim = DelegateShim(fulfill: fulfill, reject: reject)
            ExampleAPI.sharedInstance.delegate = shim
            ExampleAPI.sharedInstance.startWork()
        })
    }
}
```

Which is nice to use:

```swift
ExampleWrapper.promisedWorkResult().then { result in
    print(&quot;got \(result)&quot;)
}
```

Specifically, the advantages are:

* You don&apos;t need to conform to the delegate protocol (and thus be an `NSObject` subclass) to get the
  result.
* You can put the code that handles the result directly in-line, rather than in a separate method.


&lt;aside&gt;
&lt;span class=&quot;aside-title&quot;&gt;Note about memory management&lt;/span&gt;
I initially thought that the caller needed to hold a strong reference to the returned
&lt;code&gt;Promise&lt;/code&gt; object.  But, this actually isn&apos;t necessary.  &lt;a
href=&quot;https://twitter.com/khanlou/status/777657368616300544&quot;&gt;Soroush pointed out&lt;/a&gt; that &quot;Promises
retain themselves as long as you have any completion blocks attached to them, and they clean
themselves up on complete.&quot;
&lt;/aside&gt;


## The Problem: DelegateShim&apos;s lifetime

But, there is still a memory management problem with this specific example.  Nothing is keeping a
strong reference to the `DelegateShim` object, aside from `work` closure.  But that closure
completes (and releases its references) before the delegate callback comes (when the async
ExampleAPI work finishes).  So, the `DelegateShim` object is gone by that point.


## Possible Solutions

1. One thought I had was to make a subclass of `Promise`, specific for this use case, and have that
   hold the `DelegateShim` object as a property.  But, [Soroush&apos;s implementation of
   Promise](https://github.com/khanlou/Promise/blob/master/Promise/Promise.swift#L86) is a `final
   class` , so I couldn&apos;t subclass it.  That could be changed, but it gave me pause, because I’m not
   sure if making it `final` was arbitrary, or if there really is a good reason to force you never
   to subclass it.

2. Another idea would be to use `objc_set_associated_object()` for the promise and delegateShim, but
   that seems very unappealing, especially because it ties us back to all the ObjC runtime and
   `NSObject` baggage that I&apos;m trying to avoid.

3. If the `work` block (passed to `Promise.init(work:)` was held until the Promise fulfilled, that
   would solve this issue.  The local reference to the `DelegateShim` in that closure would be
   enough to keep it alive until it&apos;s fulfilled.  But, that requires a change to the `Promise` code.
   And, maybe that isn&apos;t good in most other use cases for Promises?  Maybe it makes it too easy to
   create reference cycles and leak objects?

4. If we want to leave Promise as-is, we can manually approximate idea #3 by blocking at the end of
   the `work` closure, so it doesn&apos;t return until we&apos;re done.  For example, we could wait on a
   semaphore that we don&apos;t signal until after the promise has been fulfilled.  That would look like
   this:

```swift
enum ExampleWrapper {

    private class DelegateShim: ExampleAPIDelegate {
        let fulfill: (String) -&gt; Void
        let reject: (Error) -&gt; Void

        /// Use this to block the `work` closure until the delegate callback comes, to keep the
        /// DelegateShim alive.
        let doneSemaphore = DispatchSemaphore(value: 0)

        init (fulfill: @escaping (String) -&gt; Void, reject: @escaping (Error) -&gt; Void) {
            self.fulfill = fulfill
            self.reject = reject
        }

        func somethingHappened(event: String) {
            fulfill(event)
            doneSemaphore.signal()
        }
    }

    func start() -&gt; Promise&lt;String&gt; {
        return Promise(work: { (fulfill, reject) in
            let shim = DelegateShim(fulfill: fulfill, reject: reject)
            ExampleAPI.sharedInstance.delegate = shim
            ExampleAPI.sharedInstance.start()
            shim.doneSemaphore.wait()   // &lt;-- This makes this block not exit until the semaphore is signaled
        })
    }
}
```

&lt;aside class=&quot;green&quot;&gt;
&lt;span class=&quot;aside-title&quot;&gt;Update&lt;/span&gt;
I&apos;ve been using solution #4 (especially after Soroush &lt;a
href=&quot;https://twitter.com/khanlou/status/777660277726863361&quot;&gt;gave a nod&lt;/a&gt;), and it&apos;s been working
pretty well so far.
&lt;/aside&gt;


## Feedback Welcome

Are there other ideas that I&apos;m missing?  Is there already a common pattern that I should use here?
Or, am I &quot;holding it wrong&quot;, for whatever reason?
[Let me know](https://twitter.com/kelan/status/777632098853105665)!</description><pubDate>Sun, 18 Sep 2016 00:00:00 GMT</pubDate></item><item><title>Playgrounds for Libraries</title><link>https://kelan.io/2016/playgrounds-for-libraries/</link><guid isPermaLink="true">https://kelan.io/2016/playgrounds-for-libraries/</guid><description>I recently noticed (in the [Interstellar](https://github.com/JensRavens/Interstellar)
project) that you can include a Playground with your Swift library.  I think this is a great way to
provide some documentation and examples, and also to give a new user a way to easily start
experimenting with using the library.

So, this is my attempt to raise awareness about this, and to ask library authors to include a
Playground in their projects.

And, to lead by example, I [just opend a pull request to add
this](https://github.com/khanlou/Promise/pull/2) to Soroush Khanlou’s
[Promise](https://github.com/khanlou/Promise) library.

### How To

It turns out to be pretty easy to do this.  If you simply include the Playground in your workspace
(or even just `.xcodeproj`), and then you make sure the `.framework` has been built (e.g. by
building a scheme in your project that includes the framework), then you can simply `import
MyFramework` at the top of your Playground, and use the public API.  I’m guessing there is some
magic that Xcode is doing to make this build/link correctly.</description><pubDate>Sat, 10 Sep 2016 00:00:00 GMT</pubDate></item><item><title>Synchronized Wrapper in Swift</title><link>https://kelan.io/2016/synchronized-wrapper-in-swift/</link><guid isPermaLink="true">https://kelan.io/2016/synchronized-wrapper-in-swift/</guid><description>&lt;p class=&quot;central&quot;&gt;
This is an idea I&apos;ve been tinkering with recently, to help enforce thread-safe access to
properties in a class instance.  It still needs some more refinement, but I wanted to write up my
thoughts and progress so far, to start to get feedback.
&lt;/p&gt;
&lt;aside class=&quot;central warning&quot;&gt;
&lt;span class=&quot;aside-title&quot;&gt;WARNING&lt;/span&gt;
This is the early formulation of an idea, and it may not even be a good idea. I&apos;m not recommending
any of this code for production use (at least not yet).  Specifically, you probably won&apos;t just
solve all of your threading issues by adding this wrapper.  But, if you are already trying to do
the right thing, this could make it a little easier to get right.
&lt;/aside&gt;
&lt;h2 class=&quot;central&quot;&gt;Background&lt;/h2&gt;
&lt;p class=&quot;central&quot;&gt;
I recently noticed a pattern in my code where I use a dispatch semaphore, or serial queue, to
achieve thread-safe access to some critical properties in a class.  This works fine, but isn&apos;t
enforcible at all.  A simple headerdoc comment of &lt;code&gt;/// -note: Only access these properties
while holding the above lock&lt;/code&gt; is way too easy to overlook, even with the best of intentions.
So, I was wondering if there was a way to have the Swift compiler help enforce this.
&lt;/p&gt;
&lt;h2 class=&quot;central&quot;&gt;General Approach&lt;/h2&gt;
&lt;p class=&quot;central&quot;&gt;
The basic idea is to wrap the critical property in something that keeps the value
&lt;code&gt;private&lt;/code&gt;, and forces you to access them only using specific methods that do the
locking/synchronization for you.
&lt;/p&gt;
&lt;aside class=&quot;central&quot;&gt;
&lt;span class=&quot;aside-title&quot;&gt;NOTE&lt;/span&gt;
The following examples are from a playground in Xcode 8 beta 6, using Swift 3.
&lt;/aside&gt;
&lt;div class=&quot;showground&quot;&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
Here&apos;s the basic definition.  We&apos;re using a simple &lt;code&gt;DispatchSemaphore&lt;/code&gt; to do the
locking.
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
class Synchronized&lt;T&gt; {
    private var value: T
    private let lock = DispatchSemaphore(value: 1)

    init(_ value: T) {
        self.value  = value
    }
}
```

&lt;/div&gt;
&lt;div class=&quot;output empty&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
It only holds a single value, but you can put multiple things in there by putting them all in
a &lt;code&gt;struct&lt;/code&gt;.  And, then you know they will always be updated together.
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
struct CriticalState {
    let title: String
    var things: [String] = []
    var sublteDerivedValue: Int = 0  // for example, this is the length of the things array
}
let criticalState = Synchronized(CriticalState(…))
```

&lt;/div&gt;
&lt;div class=&quot;output empty&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
Notice that &lt;code&gt;value&lt;/code&gt; is &lt;code&gt;private&lt;/code&gt;, so you can&apos;t access it directly.
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
let criticalString = Synchronized(&quot;test&quot;)
// This doesn&apos;t work:
print(criticalString.value)
```

&lt;/div&gt;
&lt;div class=&quot;output&quot;&gt;
&lt;br /&gt;
error: &apos;value&apos; is inaccessible due to &apos;private&apos; protection level
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
&lt;p&gt;
So, you have to go through accessor methods.
&lt;/p&gt;
&lt;p&gt;
Here is one that gives you &quot;read access&quot; to the wrapped value.  It waits for the semaphore
first, and signals it after it&apos;s done.
&lt;/p&gt;
&lt;p&gt;
As a side note, &lt;code&gt;defer&lt;/code&gt; is nice here for a few reasons.  First, it lets us return
the output of the block without having to store it in a temporary variable, and second,
because it will still signal the semaphore if we exit this scope via the block
&lt;code&gt;throw&lt;/code&gt;ing.
&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
/// The unwrapped value is passed in to the given closure, as a read-only value.  And, you can
/// then calculate some value from it (the &lt;code&gt;R&lt;/code&gt;), and return it from the closure, and
/// it&apos;s returned from the &lt;code&gt;.use()&lt;/code&gt; method.
func use&lt;R&gt;(block: (T) throws -&gt; R) rethrows -&gt; R {
    lock.wait()
    defer { lock.signal() }
    return try block(value)
}
```

&lt;/div&gt;
&lt;div class=&quot;output empty&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
Here is how it looks to use it.
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
let criticalString = Synchronized(&quot;test&quot;)
let uppercasedString = criticalString.use { string in
  return string.uppercased()
}
print(uppercasedString)
```

&lt;/div&gt;
&lt;div class=&quot;output&quot;&gt;
&lt;br /&gt;&lt;br /&gt;
TEST
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
What about modifying the value?  Let&apos;s add another method for that.
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
/// This method lets you pass a closure that takes the old value as an `inout` argument, so
/// you can use that when determining the new value (which you set by just mutating that
/// closure parameter.
/// - note: The lock is held during the whole execution of the closure.
func update(block: (inout T) throws -&gt; Void) rethrows {
    lock.wait()
    defer { lock.signal() }
    try block(&amp;value)
}
```

&lt;/div&gt;
&lt;div class=&quot;output empty&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
Which we use like:
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
let criticalString = Synchronized(&quot;test&quot;)
criticalString.update { string in
  string = &quot;new value&quot;
}
```

&lt;/div&gt;
&lt;div class=&quot;output empty&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p class=&quot;central&quot;&gt;
So, that&apos;s the basics.  It&apos;s pretty simple, really.  But, there are some subtle details and
limitations to explore a bit more.
&lt;/p&gt;
&lt;h2 class=&quot;central&quot;&gt;
Limitation with Reference Types
&lt;/h2&gt;
&lt;p class=&quot;central&quot;&gt;
Astute readers might notice that this whole approach has a fundamental flaw if the wrapped value
is a reference type.  A caller could keep a reference to the wrapped value, and mess with it
outside of the closure.
&lt;/p&gt;
&lt;p class=&quot;central&quot;&gt;
Unfortunately, I don&apos;t know of a great solution for this. If you have any ideas, please
&lt;a href=&quot;https://twitter.com/kelan&quot;&gt;let me know&lt;/a&gt;!  But, even so, I still think that this whole
concept has some value, because it&apos;s at least one step better to encouraging proper
synchronization.  You have to actively subvert it to break things, rather than simply forget to
hold a lock at the write time (pun intended &amp;mdash; sorry).
&lt;/p&gt;
&lt;div class=&quot;showground&quot;&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
A simple example of this potential for abuse would be to just return the value from the
&lt;code&gt;.use()&lt;/code&gt; block.
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
class CriticalState { … }
let criticalState = Synchronized&lt;CriticalState&gt;(…)
let unsafeReference = criticalState.use { $0 }
unsafeReference.mutate()  // &lt;-- This is bad!
```

&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
So, I actually think it&apos;s worth addressing this head-on, and making a method for this, but
naming it with an appropriate warning.
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
/// - note: If the wrapped type a reference type, you shouldn&apos;t use the return
/// value it to modify it, because that won&apos;t be synchronized after this methods returns.
func unsafeGet() -&gt; T {
    lock.wait()
    defer { lock.signal() }
    return value
}
```

&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p class=&quot;central&quot;&gt;
However, this operation is actually &quot;safe&quot; for value types, because the caller just gets a copy of
the value, so it can&apos;t then affect the thing inside the wrapper.  So, I would like to make two
different &quot;flavors&quot; of this &lt;code&gt;Synchronized&lt;/code&gt; struct: one for value types, and one for
reference types.  But I&apos;m not sure if it&apos;s actually possible to express with Swift&apos;s generics.
Again, if you have thoughts/feedback, &lt;a href=&quot;https://twitter.com/kelan&quot;&gt;let me know&lt;/a&gt;!
&lt;/p&gt;
&lt;h2 class=&quot;central&quot;&gt;
Further Questions and Issues
&lt;/h2&gt;
&lt;h3 class=&quot;central&quot;&gt;Locking&lt;/h3&gt;
&lt;p class=&quot;central&quot;&gt;
Using a &lt;code&gt;DispatchSemaphore&lt;/code&gt; as the lock is not necessarily the best choice (but was a
simple choice to illustrate the general pattern here).  For further reading, start with
&lt;a href=&quot;https://twitter.com/cocoawithlove/status/739104279202406400&quot;&gt;this thread on Twitter&lt;/a&gt;.
The major issue is priority inversion (like &lt;code&gt;OSSpinLock&lt;/code&gt;) because, as
&lt;a href=&quot;https://twitter.com/Bagelturf/status/739253535506735104&quot;&gt;Steve Weller points out&lt;/a&gt;,
&quot;Queues execute the waiters in order. Locks/semaphores use an unknown/unpredictable method
to pick next&quot;, suggesting that a serial &lt;code&gt;DispatchQueue&lt;/code&gt; would be better.
&lt;/p&gt;
&lt;p class=&quot;central&quot;&gt;
But both of those lock all access, even preventing two concurrent readers, which seems like it
should be supported.  So, something like a &lt;code&gt;pthread_rwlock_t&lt;/code&gt;, can allow multiple
readers as long as nothing is writing.
&lt;/p&gt;
&lt;p class=&quot;central&quot;&gt;
In a future post, I&apos;ll explore different locking implementations, with a way to easily swap them
out on a case-by-case basis.
&lt;/p&gt;
&lt;h3 class=&quot;central&quot;&gt;Naming Options&lt;/h3&gt;
&lt;p class=&quot;central&quot;&gt;
I&apos;m not sure what name is best (for both the whole class, and the accessor methods).
Some ideas are, for the whole class:
&lt;code&gt;class ThreadSafe&amp;lt;T&amp;gt;&lt;/code&gt;,
&lt;code&gt;class Critical&amp;lt;T&amp;gt;&lt;/code&gt;,
&lt;code&gt;class Protected&amp;lt;T&amp;gt;&lt;/code&gt;,
for the &lt;code&gt;use()&lt;/code&gt; method:
&lt;code&gt;func read()&lt;/code&gt;,
&lt;code&gt;func with()&lt;/code&gt;,
and for the &lt;code&gt;update()&lt;/code&gt; method:
&lt;code&gt;func write()&lt;/code&gt;,
&lt;code&gt;func mutate()&lt;/code&gt;.
&lt;/p&gt;
&lt;p class=&quot;central&quot;&gt;
Since it&apos;s most important to consider how they look/feel at the call site, here
are a few examples:
&lt;/p&gt;
&lt;div class=&quot;showground&quot;&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
Here&apos;s the setup
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
struct State {
    var statusMessage: String
    var items: [Item]
}
let state = Synchronized&lt;State&gt;(State())
```

&lt;/div&gt;
&lt;div class=&quot;output emtpy&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
Accessing with &quot;read&quot; and &quot;write&quot;
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
let message = state.read { $0.statusMessage }
state.write { state in
    state.items.append(Item())
}
```

&lt;/div&gt;
&lt;div class=&quot;output emtpy&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
Accessing with &quot;use&quot; and &quot;update&quot;
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
let message = state.use { $0.statusMessage }
state.update { state in
    state.items.append(Item())
}
```

&lt;/div&gt;
&lt;div class=&quot;output emtpy&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p class=&quot;central&quot;&gt;
Again, I&apos;m open to suggestions, so &lt;a href=&quot;https://twitter.com/kelan&quot;&gt;let me know&lt;/a&gt; what you think!
&lt;/p&gt;
&lt;h2 class=&quot;central&quot;&gt;Thanks&lt;/h2&gt;
&lt;p class=&quot;central&quot;&gt;
Thanks to &lt;a href=&quot;https://twitter.com/jtbandes&quot;&gt;Jacob&lt;/a&gt;,
&lt;a href=&quot;https://twitter.com/jamesdempsey&quot;&gt;James&lt;/a&gt;, and the rest of the folks at Upthere for
giving me early feedback about this idea during a discussion over lunch.  And preemptively to
anybody who has any feedback!
&lt;/p&gt;</description><pubDate>Mon, 29 Aug 2016 00:00:00 GMT</pubDate></item><item><title>Swift - didSet on Local Variables</title><link>https://kelan.io/2016/swift-didset-on-local-variables/</link><guid isPermaLink="true">https://kelan.io/2016/swift-didset-on-local-variables/</guid><description>&lt;p class=&quot;central&quot;&gt;
In &lt;a href=&quot;http://chris.eidhof.nl/post/structs-and-mutation-in-swift/&quot;&gt;Chris Eidhof&apos;s
recent post&lt;/a&gt; I learned that you can use &lt;code&gt;willSet&lt;/code&gt; and
&lt;code&gt;didSet&lt;/code&gt; on local &lt;code&gt;var&lt;/code&gt;s.  This is just a quick write-up
to explore it a bit.
&lt;/p&gt;
&lt;aside class=&quot;central&quot;&gt;
&lt;span class=&quot;aside-title&quot;&gt;note&lt;/span&gt;
The following examples are from a playground in Xcode 8 beta 6, using Swift 3.
&lt;/aside&gt;
&lt;div class=&quot;showground&quot;&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
Here is a simple example; just print out a message every time a variable
is set.  Something like this could maybe be useful for debugging?
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
var s1 = &quot;initial value&quot; {
    didSet {
        print(&quot;changed s1 to:&quot;, s1)
    }
}
```

&lt;/div&gt;
&lt;div class=&quot;output empty&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
Now change the variable, and see that our &lt;code&gt;print()&lt;/code&gt; is called.
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
s1 = &quot;new value&quot;
s1 = &quot;newer value&quot;
```

&lt;/div&gt;
&lt;div class=&quot;output&quot;&gt;
changed s1 to: new value
changed s1 to: newer value
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;h2 class=&quot;central&quot;&gt;
Recording History
&lt;/h2&gt;
&lt;p class=&quot;central&quot;&gt;
Here is another example, that keeps a history of previous values.
&lt;/p&gt;
&lt;div class=&quot;showground&quot;&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
First, set up an array to store the history of changes, and capture that
in the closure.  Note that I never said this is a good idea &amp;mdash; it&apos;s
just interesting that it&apos;s possible.
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
var history = [String]()
var s = &quot;initial&quot; {
    willSet {
        history.append(s)
    }
}
```

&lt;/div&gt;
&lt;div class=&quot;output empty&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
Now, set it a few times.
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
s = &quot;a&quot;
s = &quot;b&quot;
s = &quot;c&quot;
s = &quot;d&quot;
```

&lt;/div&gt;
&lt;div class=&quot;output empty&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
And see the history was recorded.
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
print(&quot;history:&quot;, history)
```

&lt;/div&gt;
&lt;div class=&quot;output&quot;&gt;
history: [&quot;initial&quot;, &quot;a&quot;, &quot;b&quot;, &quot;c&quot;]
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;h2 class=&quot;central&quot;&gt;
Final Thoughts
&lt;/h2&gt;
&lt;p class=&quot;central&quot;&gt;
I&apos;m not sure if this is an intended feature, or some weird side effect of the
implementation.  And, I don&apos;t know what an actual good use of it is.  But it
sure is a neat trick!  Also, you can tell this isn&apos;t a very common thing,
because Xcode&apos;s auto-indent doesn&apos;t handle it very well.
&lt;/p&gt;
&lt;div class=&quot;showground&quot;&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;doc&quot;&gt;
But, it seems like it wasn&apos;t a total accident, because of the error
message if you try to do it on a &lt;code&gt;let&lt;/code&gt; variable.
&lt;/div&gt;
&lt;div class=&quot;code&quot;&gt;

```swift
let s = &quot;initial&quot; {
    didSet { print(&quot;test&quot;) }
}
```

&lt;/div&gt;
&lt;div class=&quot;output&quot;&gt;
error: &apos;let&apos; declarations cannot be observing properties
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p class=&quot;central&quot;&gt;
I&apos;m not exactly sure what &quot;observer properties&quot; means, but at least it
correctly points out that this only make sense on things that can actually
change.
&lt;/p&gt;
&lt;h2 class=&quot;central&quot;&gt;Follow Up&lt;/h2&gt;
&lt;p class=&quot;central&quot;&gt;
Turns out, there are might be some practical uses for this after all.  My esteemed work colleague,
&lt;a href=&quot;http://twitter.com/marcpalmerdev&quot;&gt;Marc Palmer&lt;/a&gt; had an inspired idea to
&lt;a href=&quot;http://transition.io/curious-corners-of-swift/&quot;&gt;use this to implement a DSL&lt;/a&gt;, based on
his experience with Groovy.  I&apos;m familiar with similar tricks from Ruby (using
&lt;code&gt;#instance_eval&lt;/code&gt; and friends), but I never thought that kind of thing would be possible
in Swift.
&lt;/p&gt;
&lt;p class=&quot;central&quot;&gt;
Unfortunately, he noticed a problem (in an update in his post).  It appears that multiple repeated
sets to the local var get optimized out, so only the last one actually triggers the
&lt;code&gt;didSet&lt;/code&gt;. So this technique isn&apos;t quite reliable yet. But maybe there is some way to
fix this, with some further experimentation.
&lt;/p&gt;</description><pubDate>Thu, 25 Aug 2016 00:00:00 GMT</pubDate></item></channel></rss>