Advanced techniques

The playground has its own framework, XCPlayground, which can be used to perform certain tasks. For example, individual values can be captured during loops for later analysis. It also permits asynchronous code to continue to execute once the playground has finished running.

Capturing values explicitly

It is possible to explicitly add values to the timeline by importing the XCPlayground framework and calling XCPCaptureValue with a value that should be displayed in the timeline. This takes an identifier, which is used both as the title and for group-related data values in the same series. When the value history button is selected, it essentially inserts a call to XCPCaptureValue with the value of the expression as the identifier.

For example, to add the logo to the timeline automatically:

import XCPlayground
XCPCaptureValue("logo",logo)
Capturing values explicitly

It is possible to use an identifier to group the data that is being shown in a loop with the identifier representing categories of the values. For example, to display a list of all even and odd numbers between 1 and 6, the following code could be used:

for n in 1...6 {
  if n % 2 == 0 {
    XCPCaptureValue("even",n)
    XCPCaptureValue("odd",0)
  } else {
    XCPCaptureValue("odd",n)
    XCPCaptureValue("even",0)
  }
}

The result, when executed, will look as follows:

Capturing values explicitly

Running asynchronous code

By default, when the execution hits the bottom of the playground, the execution stops. In most cases, this is desirable, but when asynchronous code is involved, execution might need to run even if the main code has finished executing. This might be the case if networking data is involved or if there are multiple tasks whose results need to be synchronized.

For example, wrapping the previous even/odd split in an asynchronous call will result in no data being displayed:

dispatch_async(dispatch_get_main_queue()) {
  for n in 1...6 {
    // as before
  }
}

Tip

This uses one of Swift's language features: the dispatch_async method is actually a two-argument method that takes a queue and a block type. However, if the last argument is a block type, then it can be represented as a trailing closure rather than an argument.

To allow the playground to continue executing after reaching the bottom, add the following call:

XCPSetExecutionShouldContinueIndefinitely()

Note

Although this suggests that the execution will run forever, it is limited to 30 seconds of runtime, or whatever is the value displayed at the bottom-right corner of the screen. This timeout can be changed by typing in a new value or using the + and buttons to increase/decrease time by one second.

Running asynchronous code
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset