Is it possible to add package dependencies to a playground in Swift Playgrounds?

Swift Playgrounds supports two kinds of projects: playgrounds and app playgrounds. This article explains how to add a package dependency to an app playground. Is there a way to add package dependencies to a regular (non-app) playground?

1 Like

More generally, I’m looking for a simpler way to run a Swift script that depends on an external package I’ve written than:

  1. Running swift package init --type executable
  2. Manually adding the necessary lines to Package.swift.

Because I’m teaching Swift to novice programmers, and I fear that the above would be too many hoops. Swift Playgrounds would be a good pedagogical fit, but I’m open to alternative solutions.

Have you tried Arena?

3 Likes

Hadn’t heard of it; thanks for the tip! It does look like Arena will solve the problem. I’ll check it out.

1 Like

+1 for using Arena.

To avoid confusion, first we need to clarify some terms.

"Classic" Playground refers to the old-school .playground file created with Xcode. It contains some .swift files, .xcplayground files for versioning, and an .xcworkspace to group things together.

app playgrounds refers to the lightweight project bundle created with the Swift Playgrounds iPadOS app, or the same bundle that can also be created in Xcode nowadays, described in this doc. It is basically a miniature Xcode project for iPad.

To this date in 2024, the classic Playground doesn't allow adding Swift Packages directly from GitHub. It does allow drag-and-drop a Swift Package, as shown in this WWDC20 video, but that seems to be it.

To allow a classic Playground to have Swift Package dependencies, it needs to be hacked such like an Xcode project file. That is exactly what Arena does. By providing the project structure needed to use SPM, but still runs like a Playground, it solves the problem "Adding Swift Package dependencies to Playground".

It even works with GUI frameworks to some extent! Though it really shines at non-GUI frameworks, such as swift-algorithms.

1 Like