NEW: Master Swift design patterns with my latest book! >>

How to create interactive Swift playgrounds

Paul Hudson    April 13th 2018    @twostraws

Recently I released playgrounds demonstrating what’s new in Swift 4.1 and what’s new in Swift 4.2, and a number of folks have contacted me to ask what the process entails.

Well, to be brutally honest I made the playgrounds from scratch, by hand. The directory structure isn’t complicated, so most of the work was formatting the Swift code correctly.

If you want to do it yourself, I’ve included instructions and tips below. If you’d rather do it the smart way, I just released a GitHub project called Playmaker, which makes the whole process significantly easier – click here to check it out. Seriously, it makes the whole process much easier!

Directory structure

Xcode playgrounds are a directory with the extension “.playground”. For example, “whats-new-in-swift.playground”. Inside there should be three things.

First, a directory called “playground.xcworkspace”, which contains Xcode’s files – has this been upgraded to the latest project format, is there any saved user data, and so on. It should also contain a file called contents.xcworkspacedata, with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<Workspace version = "1.0">
   <FileRef location = "self:"></FileRef>
</Workspace>

Second, it should have a directory called Pages, which contains all your playground pages. Each playground page is its own directory inside there, using the “.xcplaygroundpage” extension. For example, “Boolean toggling.xcplaygroundpage”. Inside that is, at the very least, a file called Contents.swift, where your actual playground page content is stored.

Finally, it should have a file called contents.xcplayground, which lists all the pages inside your playground. These should be listed individually, pointing their page filename without the “.xcplaygroundpage” extension.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='6.0' target-platform='ios' display-mode='rendered'>
    <pages>
        <page name='Introduction'/>
        <page name='Derived collections of enum cases'/>
        <page name='Warning and error diagnostic directives'/>
        <page name='Dynamic member look up'/>
        <page name='Enhanced conditional conformances'/>
        <page name='In-place collection element removal'/>
        <page name='Boolean toggling'/>
    </pages>
</playground>

Inside a playground page

All the above isn’t terribly interesting; the real work is writing all the Contents.swift files for your playground pages.

This is a single file containing Swift code and Markdown comments. You start in “Swift mode” by default, just like any regular Swift file, but you switch to Markdown-formatted text using /*: then exit using */.

For example:

/*:
 The entire code to implement proposal is only a handful of lines of Swift:
*/
extension Bool {
    mutating func toggle() {
        self = !self
    }
}
/*:
 However, the end result makes for much more natural Swift code.
 */

When that’s rendered inside a playground, the comment parts will be displayed as fixed text, and the uncommented parts will be executed as Swift code – and be editable by end users.

Note: If I were writing the code for myself, I would add extra line breaks between the Swift/Markdown breaks, but these extra line breaks appear in the finished playground and don’t look good – it’s better to butt them right up against each other.

Writing your Markdown

Xcode supports a wide range of Markdown:

Place text in `backticks` to mark code; on your keyboard these usually share a key with tilde, ~.
* You can write bullets by starting with an asterisk then a space.
1. You can write numbered listed by starting with 1.
1. Subsequent items can also be numbered 1. and Xcode will renumber them automatically.
If you want to write a link, [place your text in brackets](and your link in parentheses)
# Headings start with a # symbol
## Subheadings start with ##
### Sub-subheadings start with ### and are the most common heading style you'll come across
Write a *single asterisk* around words to make them italic
Write **two asterisks** around words to make them bold

However, there are some extra tips to be aware of:

  • Xcode likes to strip out unused whitespace, so if you want to force line breaks you should use the   HTML – Xcode won’t strip that.
  • If you want to add callouts, use - important:, - note:, and - experiment: to get special formatting. For example, - important: Don’t do this will be highlighted in red.
  • The names of your Markdown files will appear in your playground, it’s better to name them “Title of Page” rather than “title-of-page”.

You can include links between your pages just by referencing their page name, for example [Home](Introduction). You can also move between previous and next pages using [< Previous](@previous) and [Next >](@next) – these will navigate using the XML table of contents you defined earlier.

 

About the author

Paul Hudson is the creator of Hacking with Swift, the most comprehensive series of Swift books in the world. He's also the editor of Swift Developer News, the maintainer of the Swift Knowledge Base, and Mario Kart world champion. OK, so that last part isn't true. If you're curious you can learn more here.

Click here to visit the Hacking with Swift store >>