Curious corners of Swift

Development

One of my esteemed work colleagues at Upthere, Inc., the granola-obsessive Kelan Champagne posted about using a little-known Swift “feature” where you can use willSet/didSet property observing syntax on local variables.

This is the kind of weird niche feature that has you reaching for oblique use cases where it might just be useful or turn into a new discovery that becomes something the provides useful new patterns in the future…

Given my past history with the Groovy language and heavy use of Domain-Specific Languages (DSLs), I wondered if we could use this to provide cheap and simple bindings from closure arguments to more complex backing models. It turns out, you can…

This technique could prove useful for providing access to a subset of properties (or pseudo-properties) of internal data structures, with mutation and validation of these values.

It’s not as nice for DSLs as Groovy’s delegate which allows you to use meta-programming to intercept all property and “function” invocations within a closure, but it gets us a step closer without requiring the pain that comes with meta-programming, plus it is less mysterious as everything you can “do” inside the closure is explicitly declared.

UPDATE

If you run the above code sample in a Playground you see something strange in the output:

There are setColour commands missing. I added debug output to didSet and it would appear that it only ever gets called once with the last value. That’s right – it looks like this pattern is not viable at all currently because the Swift optimizer does not seem to know that we have hooked into didSet and thus optimizes away the first three changes because it thinks nothing important could have happened as the intermediary values in the closure are not used explicitly in the closure.

The Author

Marc Palmer (Twitter, Mastodon) is a consultant and software engineer specialising in Apple platforms. He currently works on the iOS team of Concepts sketching app, as well as his own apps like video subtitle app Captionista. He created the Flint open source framework. He can also do a pretty good job of designing app products. Don't ask him to draw anything, because that's really embarrassing. You can find out more here.