Adding Swift to an Obj-C Project

You have an Objective-C Xcode project, and you want to add Swift code to it for the first time.

  • What do you need to do so it doesn't segfault when you launch?
  • What do you need to do so your Objective-C code can call your Swift code, and vice versa?

These notes apply to Xcode 8, and they assume an Xcode project named Project Foo. Names of build settings, etc., may change from one Xcode release to the next.

Adding Swift Code

Of course you should start by adding the Swift files to your project.

Calling Swift Code

In Build Settings, under Swift Compiler - General, ensure the value for Objective-C Generated Interface Header Name is set to Project_Foo-Swift.h.

In any Objective-C module where you want to call your swift code, add

#import <Project_Foo-Swift.h>

Ensuring Header is Created

[update 2016/11/20] In Build Settings, search for "Defines Modules", and set both values to YES (per Stack Overflow).

Calling Objective-C Code

In Build Settings, under Swift Compiler - General, enter a value for Objective-C Bridging Header. Typically this should be

Project Foo/Project_Foo-Bridging-Header.h

Unlike the generated interface header above, you may need to manually create this file in your project, using File > New > File... to create a new Header File.

In order for an Objective-C module to be visible to your Swift code, it needs to be imported from within this bridging header.

(This part is from memory.) Also, any Swift module that wants to call your Objective-C code needs to

import Project_Foo

Including Swift Std Libs

In Build Settings, under Build Options, set Always Embed Swift Standard Libraries to Yes.

Finding Code at Runtime

In Build Settings, under Linking, set Runpath Search Paths to @executable_path/Frameworks.

I keep forgetting this last one. Without it, at app launch Xcode will halt and the debug console will show

dyld: Library not loaded: @rpath/libswiftCore.dylib Reason: image not found