Adding 3rd Party Libraries to a Swift Playground

Women with Macbook

Objective

Add a 3rd party library to a Swift playground

Swift playgrounds are great for quickly trying out new ideas, it can often be a lot easier to try out concepts within a playground than a whole application. Sooner or later you are going to want to add a 3rd party library to a playground, it is not immediately obvious how to accomplish this.

I am going to show you one way of accomplishing it, using PromiseKit as an example. I found the following stackoverflow post, which gives an overview of what you have to do, it doesn’t outline the exact steps, some experimentation later, I found an approach which works.

Step 1Create new Xcode project

Create a new Xcode project, File -> New -> Project, select Single View application. Name your project PromiseKitExperiment.

Step 2Add playground to project

Add a new playground to your Xcode project, File -> iOS -> Playground, and name the playground, PromiseKitPlayground.

Step 3Add 3rd party libraries

Close Xcode, open a terminal window and navigate to the Xcode project directory, and run the following command:

$ pod init

Edit the Podfile to include the PromiseKit dependency.

use_frameworks!

pod "PromiseKit", "~> 3.0"

With Xcode closed, run the following command:

$ pod install
$ open PromiseKitExperiment.xcworkspace

In Xcode, click and hold on the scheme ‘PromiseKitExperiment’ and select Manage Schemes. Select OMGHTTPURLRQ and PromiseKit, you need to ensure you do this for each Pod you wish to import in your playground.

Manage Schemes

Step 4Import PromiseKit into playground

Open your playground file and edit as follows:

import UIKit
import PromiseKit
import XCPlayground

Promise(1).then { _ in
  return true
}.then {
  return 2
}.then {
  return Promise(3)
}.then { x -> AnyPromise in
  print(x)
  return AnyPromise(bound: Promise(1))
}.then {
  print($0)
}

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *