Using Swift Packages in Playgrounds

Xcode 12 playgrounds can now import and use Swift packages. It’s not the solution I was hoping for but it’s a step in the right direction.

I’ve written in the past about my attempts to add playgrounds to Xcode projects. That relied on using frameworks to share code between the app and the playground. I was never happy with the approach. Xcode 11 added support for Swift packages which makes it easier to share code within projects but playgrounds could not import the packages. (There are some workarounds but none that I wanted to use).

New in Xcode 12

There was a session at WWDC 2020 on using packages with Xcode playgrounds. The Xcode 12 release notes also mention that it’s possible:

Xcode Playgrounds can now import and use Swift packages and frameworks. Select the Build Active Scheme checkbox in the playground’s File inspector and ensure that the active scheme builds the package or framework target.

I wanted to explore the new Swift Algorithms package. That seems like an ideal use for playgrounds. Let’s take a look…

Importing Packages to a Playground

First the bad news. You cannot import packages into standalone playgrounds. You still need to create an Xcode project with at least one scheme/target. I’m starting with a new iOS App project (named Collections) but this will also work for existing projects:

  1. Create the playground (File > New > Playground...). I’m using a blank iOS playground. Name and save the playground in the root directory of the project. Make sure you add it to the project:

    Adding a playground to a project

  2. Next add the package dependency to the project in the usual way:

    Add package dependency

  3. When prompted enter the URL for the package repository. In this case the package is on GitHub:

    Choose package repository

  4. Make sure you’re adding the package to the target the active scheme builds:

    Add package to target

  5. If all goes well you should see the package dependency listed in the project navigator:

    Project navigator showing package dependencies

That’s all there is to it. In fact, I’ve not done anything we couldn’t already do. The difference is that starting with Xcode 12 we can import and use the Algorithms package in the playground:

// Collections.playground
import Algorithms

let scores: [Int] = [1,1,3,2,5,3]
let sample = scores.randomSample(count: 3) \\ [1, 1, 2]
let unique = scores.uniqued()              \\ [1, 3, 2, 5]

If you already have a playground added to an existing project you can enable support in the file inspector. Make sure you enable “Build Active Scheme”:

Build Active Scheme

You should then be able to import and use any Swift packages built by the active scheme. It’s not perfect, I wish I could do this with standalone playgrounds but I’ll take what I can get for now.

More Details