How Swift Playgrounds Work, Part I

Two of my favourite features of Swift are the REPL and playgrounds, because they make it easy to experiment and test small ideas. Their functionality is very similar, although playgrounds can be more accessible because they’re built into Xcode. Playgrounds also have the benefit of visual output, including live interactive views, instead of only text. So how is it that Apple’s development tools, which are based around compilation and running on a device, are able to provide such a quick feedback loop with playgrounds? I’ve been investigating this recently with the hope of learning the inner workings, replicating them and possibly even filling some gaps in the current playground functionality.

My first exposure to how playgrounds worked was a Vim plugin called SwiftPlayground.vim, which renders a playground’s line-by-line values in Vim. This was really neat! When building the playground contents it uses a compiler flag that transforms the playground code and adds a small Swift file to log out special values when executed. Then the plugin can show those in Vim. It’s surprisingly simple.

A more complicated use of playgrounds involves PlaygroundSupport, which allows you to keep a playground running indefinitely and render an interactive view in Xcode. It’s not a secret that these are implemented by running the playground code in a simulator (it always seems to be an iPad), because Xcode will let you know at the top of the window when it’s getting a simulator ready. If you’ve used playgrounds enough it’s possible that you’ve had one crash, which leaves your interactive view looking like a cropped iOS home screen. You can interact with that too!

The interactive views are such a neat feature that I’m going to focus on them. In a series of blog posts I’ll explain what I’ve learned so far about the implementation of Swift playgrounds, as well as any progress that I’ve made in re-implementing them from scratch while standing on some tall shoulders.