Test Driven Development in Xcode Playgrounds

Last updated: December 25, 2019. Original version: Mar 27, 2017

apple developer xcode swift swift 5 ios swift ios 13 tutorials tutorial guide free xcode playgrounds playgrounds test driven development test tests tdd teaching

Apart from being an awesome code prototyping tool, the Xcode Playgrounds can also be used for Test Driven Development. For a refresher on TDD see this Wikipedia page.

Let’s say we’re designing a struct to represent Todo items:

struct Todo {

We’ll add its associated tests (well, one for now):

class TodoTests: XCTestCase {
      override func setUp() {
      override func tearDown() {
      func testTodo() {

In a typical workflow, you will have to prop up an entire project (with a test target) to simply run this tests. Here is an faster alternative — everything in a playground:

TDD in an Xcode playground

The “magic sauce” here is the creation of a test suite for the XCTestCase subclass and running it.


The output will show in the Debug area:

Executed 1 test, with 0 failures (0 unexpected) in 0.042 (0.044) seconds


The biggest advantage of this solution is the playground (re)running all your tests every time something changes shortening the feedback look drastically!

This is similar to how guard-rspec works in the Ruby world.

Obviously, this solution can be extended by moving the struct and tests in separate files and only trigger them from the playground page. Those source files can then be shared with the Xcode project to avoid duplication or having to move the code across.

Teaching tool

This method is an awesome teaching technique — I’ve used it with great success recently!

By having tools that shorten the feedback loop, developers will actually seek to write tests as they’ll learn new APIs and design patterns.

And... there is no excuse not to Unit-Test now! 🤓