How to use playground in Swift file

Issue #998

Traditionally, if we wanted to quickly test a function or a piece of logic, we would open a separate Playground file (.playground).

From Xcode 26 we can have access to the new #Playground macro in Swift 6.2. This allows us to declare a block of code that can be executed on its own, just like a regular playground, but it lives within your app’s source code. Being in the same file allows the playground code to access private entities in the file.

Here’s an example. Let’s say we have a file called Fibonacci.swift

/// Calculates the nth Fibonacci number.
private func fibonacci(_ n: Int) -> Int {
    if n <= 1 {
        return n
    }
    return fibonacci(n - 1) + fibonacci(n - 2)
}

import Playgrounds

#Playground("Fibonacci Example") {
  for n in 0..<10 {
    print("fibonacci(\(n)) = \(fibonacci(n))")
  }
}

Because this function is private, we normally couldn’t call it from a separate playground file. But with the #Playground macro, we can test it in the very same file.

To do this, you just need to import Playgrounds framework. Then we can view the execution flow in the Assistant panel

Image

Read more

Written by

I’m open source contributor, writer, speaker and product maker.

Start the conversation