How to use your own frameworks in Swift playgrounds

With the new beta of Xcode Apple added support for importing custom frameworks to Swift Playgrounds. Let’s explore the way to use them.

We’ll start with a new Cocoa Touch Framework project:

Let’s call it MyFramework. I have selected Objective-C as a main language as I heard of some issues of creating pure Swift frameworks, and also there’s no problem in adding Swift files to Objective-C framework as well.

Now let’s add a class to our framework:


#import <Foundation/Foundation.h>
@interface MyClass : NSObject
- (NSString *) greeting;


#import "MyClass.h"
@implementation MyClass
- (NSString *) greeting {
    return @"Hello from Framework";

Next we need to add MyClass.h to framework umbrella header and make sure it will be copied to framework bundle:

Add this line to MyFramework.h:

#import <MyFramework/MyClass.h>

And change MyClass.h visibility to Public:

Ok, now let’s create a playground using our framework. Select MyFramework project and create a Workspace via File menu:

And create new Playground:

I selected iOS playground and Workspace as Group.

Now let’s build our framework to be used in Workspace. First, select iOS Simulator for iPhone 5S (64 bit) as a target. It’s important to build for 64 bit, because the default setting is to build framework only for current architecture, and playground uses 64 bit one.

And finally:

import MyFramework
MyClass().greeting()           # =>  "Hello from Framework"

Not that difficult, right? And we have a powerful way to play with our existing code in playground.


Now read this

JSON mapping and reader monad [DRAFT]

Functional JSON mapping became a hot theme recently. Clear declarative syntax backed by cryptic concepts of monads and applicative functors has exploded many heads. I’d like to talk about a little refinement of our mapping pattern to... Continue →