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:
step1.png

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.
step2.png

Now let’s add a class to our framework:

MyClass.h

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

MyClass.m

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

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:
step4.png

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

And create new Playground:
step6.png

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.

 
159
Kudos
 
159
Kudos

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 →