Learn: how to write a property wrapper that avoids boilerplate for your asynchronous callback code.

The Solution Code

Want to skip to the answer? Variables marked with this property wrapper will be destroyed after they are read once. Use with caution!

Now lets see how we got here.


Avoiding multiple invocations of a completion block

Let’s say we have a class that does some work, and then invokes its completion block.

This code has a secret bug in its check method. Did you notice it?

If someCondition gets evaluated as false, the completion block will be invoked twice – once by handleFailure(), and again by handleSuccess(). This is a bug – the completion block should only get called once.

Now obviously in this trivial example you could fix this by just using an else statement. But in The Real World, your code may be much more complicated, and it may be harder to make the calls of the completion block mutually exclusive.

Perhaps your code is asynchronous, and completes when the first of two operations returns a result, for example.

I’m not judging how you have gotten yourself into this problem – just providing a neat solution.

How to solve this problem

Our approach here is going to be to ensure the completion block can only be called once by destroying it once it has been used. One perfectly reasonable approach to this solution is as follows:

Here we are simply setting the completion closure to nil after we use it. This is fine, but requires us to add extra boilerplate around each usage of the callback. It is also error-prone, since we could easily forget to include the self.completion = nil and end up with a partial solution.

So instead, lets create a property wrapper that changes the behaviour of the getter for that variable.

What is a property wrapper?

Property wrappers are structs that use Generics to define extra behaviour around the usage of some arbitrary property. They are defined separately from the property they act on, and can be re-used easily for different properties, even of different types.

NSHipster has a great write-up on the background and purpose of this Swift feature if you haven’t seen it before so I won’t go into more of those details here.

The ReadableOnce property wrapper:

I included this at the top, but lets look in more detail at our property wrapper:

The property wrapper definition is just a struct marked with @propertyWrapper. It has a special var called wrappedValue, which is the place we have to implement whatever our custom logic is.

In our case, we want to put our magic into the get method of the value, so that the value is destroyed after being returned the first time. The set method should behave as normal, so we just add a private backing variable, here _value.

The defer keyword

Deferred closures are executed at the end of the scope they are declared in. In our case, the defer keyword allows us to execute our cleanup code after the return value is returned.

Using @ReadableOnce in the NumberChecker

Here’s what our NumberChecker looks like if we use our new property wrapper:

It would be a good idea to fix that secret bug, but even with it this code will now work as expected.

Downsides of this approach

The biggest concern with this is precisely the magic that makes it useful. It is unintuitive that you can only read once, and that reading could mutate the value.

The following code demonstrates the most likely pitfall:

Overall, I think this property wrapper is very useful, as long as it is clear to the developer that it is being used.

So basically:

With great power comes great responsibility.

Uncle ben. yes. from spiderman.

Possible Improvements

There are a number of things you might continue to experiment with to improve this solution:

  • Use a different property wrapper to accomplish the same task
  • Implement something like a callThenDestroy() method on the type you want to store
  • Try @dynamicCallable (see this Hacking With Swift post for info)
  • Thread safety has not been considered in this implementation. It would be possible for two threads to both get access to the variable before either of them set it to nil.

This article is based on a code sample shared with me by Josh Caswell (https://github.com/woolsweater)


Have you tried any of the above? Do you have a better solution? Please leave a comment below!


If you liked this post you might also like my guide on how to do high-bar code review without being a jerk.

Please follow and like us: