Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse Swift code in other projects?

Tags:

xcode

ios

swift

I wrote a class in Swift. I want to use this code in two separate iOS app projects that I wrote. Both the shared code and the apps are written in Swift. What is the best way of doing that?

I tried to create both a framework and a library in Swift and then add it as a sub-project to my app. In both cases I could not make the app see the module. I tried to add the shared module to "Target Dependencies" and "Link Binary With Libraries" of the main app's target. No luck - the app still can not see the classes of the shared module.

Using Xcode6 Beta6 at the moment.

Solution

As Konstantin Koval and Heliem pointed out, all I needed is to use public in my class and method declarations, in the shared module. Now all works, both if I use workspace and if I add the module as a subproject.

Update

I just found an excellent easy solution for reusing code between projects in Swift. It is called Carthage (https://github.com/Carthage/Carthage). This is not a plug as I am not affiliated with it in any way, I just really like it. It works in iOS 8+.

like image 274
Evgenii Avatar asked Aug 27 '14 02:08

Evgenii


1 Answers

  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'
like image 192
Kostiantyn Koval Avatar answered Oct 07 '22 06:10

Kostiantyn Koval