Swift static library in Objective-C

Xcode 9 added the ability to create static libraries with Swift code. Everything works great if you have an all Swift project, you link your library, import the module and away you go. To get your shiny new static library to be visible in Objective-C you need to do a little more work.

These instructions are based on a setup where you will build the static library as a subproject of your main app, you'll need to make adjustments as required if this does not mirror your setup.

Step 1 - Create/configure the subproject

  • Create the subproject using File -> New -> Project -> Cocoa Touch Static Library.

Cocoa Touch Static Library

  • Give the project a suitable name and click Next

Give the project a name

  • Add the static library project to your existing project

Configuring the save file dialog


Step 2 - Link the static library with the main project

  • Navigate to the target's General tab for your main app

Navigate to your target's `General` tab

  • Add the static library to Linked Frameworks and Libraries using the + button

Link library

For a pure Swift project you should be done now. For a mixed project carry on.


Step 3 - Add the generated swift header to the search path

  • Navigate to the Build Phases of the static library

Static Library `Build Phases`

  • Add a new Run Script Phase with the following code and give it a sensible name
target_dir=${BUILT_PRODUCTS_DIR}/include/${PRODUCT_MODULE_NAME}/

# Ensure the target include path exists
mkdir -p ${target_dir}

# Copy any file that looks like a Swift generated header to the include path
cp ${DERIVED_SOURCES_DIR}/*-Swift.h ${target_dir}

Static Library `Build Phases`

At this point you should be able to import the static library using #import <FeatureA/FeatureA-Swift.h> and start using your Swift code that is annotated with @objc.


Step 4 - Create a ModuleMap

Depending on how your project is set up you can run into issues where the generated swift file for your main project imports the new static library. The issue here is that it will import using module syntax (@import FeatureA;), which your project will not currently understand.

  • In your static library project create a file called module.modulemap and populate it with something like the following
module FeatureA {
    header "FeatureA-Swift.h"
}
  • Navigate to the Build Phases of the static library project

Static Library `Build Phases`

  • Add the module.modulemap file to the Copy Files phase of your static library

Update `Copy Files`


Wrap up

Following the steps above should get you working with a Swift static library within a mixed Swift/Objective-C project much quicker than I did.


Extras

Whenever I read a post like this I'm obviously grateful for the tips, especially if they help resolve the thing that was blocking me, but I'm always left wondering how someone worked it out in the first place. Here's some rough retrospective notes on the things I did to figure out the above.

Check search paths

I examined all the search paths - you can view these in Xcode by searching in Build Settings. The one that I was mainly investigating was Header Search Path, this setting is blank by default.

I noticed that the Static Library project sets its Copy Files subpath as include/$(PRODUCT_NAME) so I made the assumption that this directory will be searched.

Examine derived data

I started to look in the Build Products Dir to see if I could find my generated Swift.h file but couldn't see anything. You can get to the Products folder by expanding the Products folder in Xcode and then right clicking an item (like the static library) and selecting Show in Finder.

At this point I was started to think that maybe the generated header just wasn't being created and this wasn't meant to be.

Examined the build logs

I was just looking to see if there were any errors I had missed or anything else to help me out. This is when I noticed a phase called Copy FeatureA-Swift.h ... - BINGO. The header is indeed being created it's just being put in a place that is not on the search path.

This is when I added the Run Phase Script from above. It basically copies any files following the name *-Swift.h from the DerivedSources folder to the include folder.

ModuleMap

In my particular project I ran into the problem where the main project's generated Swift file imported the library. This meant that the library was being imported using module syntax. This step was not too difficult, I just read a few blog posts on creating a module.modulemap file and got it done.

Extra wrap up

I've tried to give some insight into the things I did to resolve the issue but reading the above can still be misleading. Taken at face value it looks like I just followed a few systematic steps to get to a solution but the reality was that this debugging took many hours, lot's off googling, lot's of swearing and muttering to myself, a few good nights of sleep and a lot of perseverance. Hopefully someone might find this useful (probably just me in a few weeks time when I have forgotten the above).

Quick Tip: Test functions with DI

Testing your code's collaborators is really important but how do you test functions like UIImage(named:) or NSLocalizedString(_:tableName:bundle:value:comment:)?


What are we testing?

We are not interested in testing whether methods like UIImage(named:) actually work as that's Apple's job but we should verify that we invoke the functions with the correct arguments.

Take the following example

class Images {
    
    func jumpSprite(atIndex index: Int) -> UIImage? {
        return UIImage(named: "jump_\(String(format: "%03d", index))")
    }

}

The above is a simple call to UIImage(named:) with some simple logic to build the image name based on the passed index. The thing that we need to test here is the image name construction logic - we would like our tests to verify that if we call the function with the input of 1 that it will invoke UIImage(named: "jump_001").


Dependency Injection to the rescue

To create a seam that allows testing the collaborator we can make UIImage(named:) injectable. Our production code can continue to use UIImage(named:) but our tests can use a different function that allows us to capture and verify the input.

Start by making it injectable with a sensible default

class Images {
    
    var loadImage = UIImage.init(named:)
    
    func jumpSprite(atIndex index: Int) -> UIImage? {
        return loadImage(named: "jump_\(String(format: "%03d", index))")
    }
    
}

In the above we made a couple of changes

  • Added a new variable of type (named: String) -> UIImage? that holds our image loading function
  • Invoke loadImage(named:) instead of directly invoking UIImage(named:)

End by adding some tests

Now that we have done the scaffolding we can add tests that verify that the correct arguments are provided when loading images

class ImagesTests: XCTestCase {
    
    func testJumpSpriteIsInvokedWithTheCorrectArguments() {
        let images = Images()
        
        var captured: String?
        
        images.loadImage = { name in
            captured = name
            return nil
        }
        
        images.jumpSprite(atIndex: 321)
        
        XCTAssertEqual("jump_321", captured)
    }
    
}

Conclusion

The fact that functions are a first-class type in Swift means that it is super simple to use dependency injection to enable testing of functions. It's always important to test our code's collaborators to ensure that we are calling their contracts correctly and with the arguments that we expect to send.

Pro Tip: Playback Speed

Videos are a great way to consume information but they can sometimes drag their feet when it comes to getting to the important subject matter. When reading a blog or a book you can just skim read over the things you already know but this is difficult with video. I generally watch most programming podcasts/tutorials or conference talks at 2x and then just slow down when I need to take more time to digest the content.

Native video

I use iTunes to subscribe to a few great podcasts like RubyTapas, NSScreencasts etc. The content is often great but the podcasts are aimed at a broad audience and so some things I can happily skim over. I don't know if there is a better podcast player I should be looking at but I generally just open the podcast in QuickTime which allows my 2x playback.

Youtube

There is too much great content to call out but Confreaks is one of my favorite channels for interesting talks. To get 2x playback speed on Youtube you need to ensure that you are using the HTML player.


The other obvious benefit to watching things at 2x speed is that they take half the time to watch. This is awesome especially if you are following series like Handmade Hero where the videos can easily be between 1-2 hours. It may not be possible to watch a whole video at 2x when it is dense with information but at least you can budget your time more wisely by skimming the less important details.