Using 3rd party frameworks in Swift Playgrounds
For updated instructions (Swift 5 and Xcode 11), please visit: https://www.pardel.dev/blog/3rd-party-frameworks-in-xcode-playgrounds
Xcode Playgrounds is a great place to prototype code and even practice Test-Driven Development. And sometimes, 3rd party libraries might be handy to use. In our case, we’re going to use Realm.io in a playground.
The problem we’re trying to solve
3rd party frameworks can’t simply be included in a playground, not even as part of “Sources”:
Before we start
Realm framework is available for Swift in a binary form — at the time of this writing the version available is 2.5.0 which comes with binaries for Swift 3.0, 3.0.1, 3.0.2 and 3.1. I’m gonna be using Xcode 8.3 (with Swift 3.1).
Download Realm Swift 2.5.0 from realm.io. Expand the downloaded archive and navigate to ios > swift-3.1. We’re going to use the 2 frameworks provided:
The Playground
Let’s create the playground that’s we’re going to use — make sure it’s an iOS playground (I’ve named mine: “MyRealm”), stored it on the Desktop and close it down for now.
The Solution: include required frameworks into an own Cocoa framework
The solution is to create a Cocoa framework that encapsulates the required 3rd party frameworks.
Step 1 — create the framework
From the menu, File > New > Project, and select “Cocoa Touch Framework”. I’ve named my “FrameworkWrapper”.
Sidenote: no need to tick the “Include Unit Tests” checkbox.
You’ll end up with a standard project layout:
Step 2 — include the 3rd party frameworks
Drag & Drop the 2 Realm frameworks — make sure you select the right version based on the Swift version you have. Tick “Copy items if needed”.
We’ll also need to add a “New Copy File Phase” to the Build Phases, set its destination to Frameworks and include the 2 Realm frameworks:
Make sure that the FrameworkWrapper builds without errors (Cmd + B).
Step 3 — add the playground
We’ll drop in the playground we created earlier making sure “Copy items if needed” is checked.
Now, the framework we created can be imported into the playground but its included frameworks cannot:
Step 4 — the “missing link”
You’ll be surprise to hear that all you need to do is create an empty .swift file so the compilation process includes the Realm frameworks; the name doesn’t matter much — I’ve named mine the same as the framework:
Build the framework again (Cmd + B) and you’ll notice that the previous error goes away and you’ll be able to create Realm objects:
That’s it!
Happy Prototyping! 🤓
Update April 5th
The Video of my “TDD in Xcode Playgrounds” lighthing talk at @iOSConLondon can be found below. It covers the subject of this article as well as others.