The Evolution of Swift Playgrounds

Francesco Marisaldi
The Startup
Published in
8 min readJun 11, 2020

“An amazing platform to learn coding, a great developer tool” is a good definition for Swift Playgrounds, because it summarises two main use cases the platform gives us: on one hand, a way to learn coding (in Swift) with a challenge based approach, where learners are guided in the learning process with incremental steps, concepts and tools, tailored to get programming to more people. On the other hand, a great developer tool to run Swift code on iPad or outside a classic Xcode project/workspace, giving developers the chance to prototype features, easily test interactions which require device capabilities (like accelerometer), isolate issues from large codebase, create learning experiences: in few words, it’s the fastest way to code with Apple’s APIs.

I enjoy using Swift Playgrounds in my developer life and since I won a WWDC Scholarship back in 2018. In this article, I want to dive into the evolution of playgrounds and point to some interesting features, use cases and ways to craft a good playground.

From the Introduction to the Mac app

Playgrounds were first introduced in 2014: Xcode > New Playground was the easier way to start experimenting with the brand new Swift language. One year later, Playground in Xcode 7 was updated with inline results, pages, markup. In 2016, the Swift Playgrounds iPad app was launched, with code challenges designed by Apple to learn coding and the new playgroundbook format. From there, the app has gained new features every year: ARKit and camera access, Playground Support and Bluetooth frameworks, most of iOS SDK frameworks, 3rd-party subscriptions, just to mention some of them.

With the 3.0 version, modules arrived in Swift Playgrounds: folder of Swift files shared across the book with multiple access control levels available, enabling modularization, scalable and reusable code. While Xcode Playground remains a great developer tool, the Swift Playgrounds app has covered during time not only the learn coding side, but even many developers use cases, as mentioned in the introduction, with a important issue: playground books were running only on iPad. Until March 2020, when Swift Playgrounds for Mac was released.

Swift Playgrounds Mac and iPad apps, Xcode Playground

.playground vs .playgroundbook

As you may already know, a playground usually comes with an editor view on the left, which contains code and (eventually) prose with markup and annotation features; and the live view on the right (if setted). The result sidebar shows a representation of values on corresponding line, customizable using the CustomPlaygroundDisplayConvertible protocol. But, as I wrote above, when we talk about playgrounds, there are two available formats: the .playground and the .playgroundbook. What are the differences?

The .playground is available from the very beginning: it’s the only format compatible between Swift Playgrounds apps and Xcode, enabling seamless workflow. In fact, you can create a .playground right on the iPad, using the “Playground Xcode” template, and then open the file on the Mac, both on Xcode or from the app. With a standard playground you can create multiple pages, write prose with markup, but modules are missing (even if there are shared and page relative sources). It’s the right choice if you need to switch between Xcode and iPad frequently, with full compatibility, having an immediate on-device feedback while implementing features. Some other powerful features of .playground come from the integration with Xcode: you can read more about them in the last section.

On the other hand, there’s .playgroundbook: the default format when you create a new document from standalone apps, it has a package-based structure defined by folders and plist files.

.playgroundbook structure

It comes with exclusive features, including already mentioned modules, to organize and modularize code; chapters, to group playground pages with the same topic, and cutscenes, which are fullscreen pages (in HTML or Swift) to show introductions or explanations; a key-value persistent storage, to save data and load it across multiple sessions; a glossary, to define terms cited in the page’s prose; and a system of hints, spoilers and solutions to help learners progress through page’s challenges.

With the exception of modules, these features are focused on learning experiences. For this reason, the book format is the right choice if you want to create rich learning experiences and tutorials; but it’s a powerful tool to code and prototype without Xcode as well. As now, Xcode can’t even run a .playgroundbook, even if it’s possible to open a book, navigate and modify its structure and files.

PlaygroundSupport Framework

In order to take advantage of all playground’s features, you should use the PlaygroundSupport framework, which enables you, according Apple’s documentation, to:

Access a playground page and manage its execution, as well as manage live views; access and share persistent data; assess the progress of the learner, update hints, and show success text

First, setting the live view: by doing so, playground is able to render your UI stuffs. Live view can be any UIView, a controller, or even SwiftUI View:

PlaygroundPage.current.setLiveView(Text("🤓"))

Playground runs in a synchronous way, so it terminates once the last line of code has been executed: this is a problem if you want to work with asynchronous code. To run playground asynchronously, you either set a live view or use the dedicated api:

PlaygroundPage.current.needsIndefiniteExecution = true

You can import files in playgrounds and use the Bundle.main api to access them. As said, books are able to persist data across sessions, by get or set:

PlaygroundKeyValueStore.current["your-key"]

By default, live views run in the same process of playgroundpage’s code: the good is you can access them directly, the bad is that run command reset everything. Playground book offers the feature to run an always-on live view in a dedicated process: this means it persists through different runs, enabling you to edit and run code on the editor. How to communicate between an always-on live view and the playground page? Let’s see an example: we want to send our mood to an always-on view responsible to display it. To configure an always-on live view, we have to put a Live.swift file inside the playgroundpage, where we call the setLiveView function: unfortunately, we can’t do this on standalone apps, so we need to edit the structure of the book from the Mac or use the Xcode template (see next section for more details). After that, we can send our Mood from the playground page using:

The full list of types you can send as messagges is available here. To handle messages, just adopt the PlaygroundLiveViewMessageHandler protocol on the object set as live view, in our case a UIViewController:

And we did it! Use Messenger.send(.happy) from the page, run it and the live view will be updated. Similarly, to send messages from the live view to the page, there’s the PlaygroundRemoteLiveViewProxyDelegate protocol: you can find full framework doc here; the Moods book is at the end of this article.

The Moods book in action

Standalone apps, Authoring Books, Xcode Playground

Other than formats, the tool you decide to use makes the difference in the playground world. With standalone apps, you’re able to create complex books; code from iPad and then continue on Xcode using the .playground format; more in general, to handle many use cases other than learn coding. And of course, it’s the only way to run books.

When talking about authoring books with rich learning experiences, you can’t rely just to the app. First, you can’t edit the prose in the editor; well, you can, for example, type /*:This is a sentence*/, close the book, open it again and the sentence will be rendered as prose but… you can’t modify/delete it anymore 🤯. Same happens to annotations like editable regions or hiding: there’s not a rendered-raw markup switch. Moreover, from the apps you can’t create chapter, cutscenes, glossary, hints, handle messages between always-on live view and editor (as we saw above).

For these purposes, you have to edit the book by modifying its structure, plists, sources and resources on a code editor. If you want to start a new book from scratch, Apple provides an Author Template: it’s a Xcode project where you create the entire book’s structure and contents. When you build the project, a .playgroundbook is created, ready to be exported. Being integrated in Xcode, the template offers many benefits: for example, an easier way to use storyboards (compiled stoyboards are packaged in the book) and test the UI.

Before the conclusion, Playground in Xcode deserves few more words, because it covers some other powerful use cases for developers. First, before the introduction of CreateML, playground in Xcode was the easier way to train a CoreML model right on the Mac. The editor is able to show formatted or raw markup: a unique feature to create prose and check it immediately. In addition, there’s dedicated api to customize TouchBar contents; and the step by step execution (using the tool on the left of the editor) allows to run single lines of code, having the chance to respond to live data. Playground in Xcode can even import 3rd-party frameworks as showed in a WWDC18 session, in order to show or test framework’s api: having a framework target, drag the framework project into the playground’s window and it will be converted in a workspace, build the framework and you can import it into the playground.

Someone pointed to Swift Playgrounds app as a sort of “light Xcode for the iPad”; the release of Swift Playgrounds for Mac (and the rumoured Xcode porting for the iPad?) clarifies one more time they are two different products, with different use cases. But what about next steps? I would love to see an easier way for authoring playground books; a better integration with Swift Package Manager; or some brand new APIs in the PlaygroundSupport framework.

Here’s some useful resources, including the link to download the playgroundbook sample, full Apple’s documentation and a playlist of WWDC videos about playgrounds. Thanks for reading! ☕️

--

--