Topics

Topics

One of the most useful parts of Xcode Playgrounds is the way they allow us to visualize our code. We can click the Quick Look button, or insert a preview directly into our code with the Show Result button in the Results sidebar:

We can add visual representations to the assistant timeline using XCPlayground's captureValue function (Bite #136).

This can be incredibly handy for spotting problems quickly:

Tons of system types are supported like CGPath, NSURLs, and even many of SpriteKit's classes. These are actually the same representations that can be seen if we Quick Look something while debugging in Xcode.

We can add these capabilities to our own custom types (for both debugging andPlaygrounds) by adding a function like this to them, returning a supported type:

funcdebugQuickLookObject()->AnyObject?{returnname}

This is great, but only works on types that inherit from NSObject and won't work for things like Swift structs. Also, even though we're adding this to our own type, we'll still need to return one of the built-in, Quick Look-able types supported by Xcode.

For more flexibility, let's look at XCPlayground'sXCPlaygroundLiveViewable protocol.

This will let us visualize our own types by returning a view or view controller that will be shown in the assistant timeline when we capture a value:

Topics

Topics

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:

importXCPlayground

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:

XCPlaygroundPage.currentPage.finishExecution()

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'sliveViewproperty 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: