How to create and use a framework in Swift?

Recently I wanted to create a simple framework in Swift to use it in other projects. I couldn’t find a simple tutorial, so I decided to write one myself.

First of all, create a new Xcode project and select the template called ‘Cocoa Touch Framework’. In the next screen give your framework a name, select Swift as the language and save it to a convenient location. My framework is called ‘TutorialFramework’.

new swift framework dialog

The next thing to do is to edit the scheme, so that the framework will run in release mode instead of debug mode. Select Product -> Scheme -> Edit Scheme (or press Command – <). Make sure ‘Release’ is selected in the build configuration setting of the run scheme.

Xcode select run scheme

As you can see, the template created a TutorialFramework.h header file. Leave it there. Next, press Command-N to create a new file. Select an empty Swift file and name it whatever you like. I called mine SayHello.

Select new Swift file

Next, copy and paste the following code into your new Swift file:

It is important to use the keyword ‘public’ before the class and functions. Otherwise, the code will not be accessible outside the framework itself.

Next, press Command-B to build the framework. Do not forget this. After building the code, Control-click on the framework product in the file navigator and select ‘Show in finder’.

Show framework in finder

framework in finder

Option-drag the .framework file to a convenient location. You can now close the Xcode framework project.

To use the framework in an app, create a new Xcode project and select the ‘Single View Application’ template. Select Swift as the language and name the project whatever you like. I called mine FrameworkTestApp.

new project dialogThe next step is linking your framework to the newly created app. Before linking it, it is convenient to drag the .framework file into the project folder of the new app. Now, select the app target and select the ‘general’ tab in the app settings. Scroll to ‘Embedded Binaries’ and press the ‘plus’ icon to embed a new binary.

Test app overview

Click on ‘Add Other’, select the .framework file in the finder and click ‘Open’.

add other framework

In case you copied the framework file to your project folder, you can leave the ‘Copy items if needed’ checkbox unchecked in the next dialog. Click ‘Finish’. Now, you can see that your framework has been linked to the app.

Embedded binaries Xcode

Now press Command-B to build your app. This shouldn’t be necessary, but it often helps Xcode to ‘recognize’ your framework so you can use it in your code. To use your framework code browse to the ViewController.swift class and add the following import statement:

After importing your framework, you can now use it. Copy and paste the following code in the viewDidLoad method:

Run your app. Your console will read this: