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 and Playgrounds) by adding a function like this to them, returning a supported type:
func debugQuickLookObject() -> AnyObject? { return name }
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's XCPlaygroundLiveViewable 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:
extension Person : XCPlaygroundLiveViewable {
func playgroundLiveViewRepresentation() -> XCPlaygroundLiveViewRepresentation {
let vc = PersonLiveViewableViewController(person: self)
return .ViewController(vc)
}
}
Now, we can set our current page's liveView
to a instance of Person directly, and we'll see our custom view controller appear in the assistant timeline. Neat!
XCPlaygroundPage.currentPage.liveView = Person()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true