#136: XCPlayground Basics πŸŽͺ


Xcode Playgrounds arrived in Xcode 6. They're a great way to try out some code quickly, or to learn about an API or library through interactive documentation.

Playgrounds are unbelievably useful out-of-the-box, but today we'll look at a framework called XCPlayground that makes them even better.

XCPlayground ships with Xcode. We can import it in our Playgrounds to enable all sorts of interesting functionality.

We'll begin by creating a new Playground. We can do this by selecting File > New > Playground… from Xcode's menu (or βŒ₯β‡§βŒ˜N). Then we'll import XCPlayground:

import XCPlayground

Let's start with one of the most common reasons for importing XCPlayground, indefinite execution. By default Playgrounds execute the code in each page, from top-to-bottom, then they stop executing. We can change this behavior like so:

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

This will allow any asynchronous code we have in our Playground to continue running indefinitely.

Once our code is done, we can call:


Another great use for Playgrounds is prototyping views. We'll need to enable needsIndefiniteExecution first, then:

XCPlaygroundPage.currentPage.liveView = containerView

We set the current page's liveView property to any UIView or NSView and it will appear visually in the assistant editor.

If the assistant editor isn't already visible, we can open it by selecting View > Assistant Editor > Show Assistant Editor from Xcode's menu (or βŒ₯βŒ˜β†©οΈŽ).

Similarly, we can add a value to the assistant editor (including a corresponding label so know what's what) like this:

XCPlaygroundPage.currentPage.captureValue(containerWidth, withIdentifier: "Width")

We'll be looking at more neat features of Playgrounds soon. Please send your favorite Playground tips to!