How to reuse Swift code in other projects?

Here is a video which is very straightforward: http://eonil-observatory.tumblr.com/post/117205738262/a-proper-way-to-add-a-subproject-to-another-xcode

The video is for OS X instead of iOS. But you will get it and figure out the process for iOS.

Let's assume that AppA needs to reused code from SharedProject.

The following process works for me in Xcode 7 Beta:

  1. Create SharedProject. Project type must be Framework instead of Application. You write common code in this project and mark the code as public.
  2. Open AppA in Xcode, open the folder which contains SharedProject in Finder. Drag the .xcodeproj file of SharedProject from Finder and drop it into the root folder of AppA in Xcode Project Navigator.
  3. AppA --> Build Phases --> Link Binary with Libraries. Add SharedProject.
  4. import SharedProject and reuse code from SharedProject!

Edit:

Nowadays I suggest you use Carthage. It's better than the home made solution above.


  1. Create a new project (iOS Cocoa Touch Framework) for your reusable code
  2. Move your classes to that Framework project
  3. Mark your methods and classes, that should be visible to others as public
  4. Create Workspace.
    You can create a workspace on step 1. When you create new Framework project, Xcode will ask you if you want to create new workspace and add that project to workspace. This is the best approach
  5. Add both your project and Framework to the workspace
  6. Select you project target -> General tab. Add Framework and Libraries (add your library here)
  7. When you want to use code from your Library in swift file, import it using import 'LibTargetName'

You can take a more programatic approach by using SWM (Swift Modules): https://github.com/jankuca/swm

It is very similar to npm (node.js package manager) or bower (client-side module manager); you declare your dependencies in a swiftmodule.json file like below. It does not have a central module registry like the two mentioned JS solutions, it only accepts git URLs.

{
  "name": "ProjectName",
  "dependencies": {
    "Dependency": "git://github.com/…/….git"
  }
}

…run swm install and have the Dependency module (compiled into a *.swiftmodule binary) ready for import in the .modules/ directory.

import Dependency

And if you prefer to skip Xcode for app development, you can also build your whole app using swm build (more info in the project's readme).

The project is still in early stages but it makes itself useful a lot for me at least. It provides the most clean (and clear) way of creating importable modules.

Tags:

Ios

Xcode

Swift