Swift and Objective-C interoperability
Using Objective-C Classes in Swift
If you have an existing class that you'd like to use, perform Step 2 and then skip to Step 5. (For some cases, I had to add an explicit
#import <Foundation/Foundation.hto an older ObjC File)
Step 1: Add Objective-C Implementation -- .m
.m file to your class, and name it
Step 2: Add Bridging Header
When adding your
.m file, you'll likely be hit with a prompt that looks like this:
Click YES !
If you did not see the prompt, or accidentally deleted your bridging header, add a new
.h file to your project and name it
In some situations, particularly when working with ObjC frameworks, you don't add an Objective-C class explicitly and Xcode can't find the linker. In this case, create your
.h file named as mentioned above, then make sure you link its path in your target's project settings like so:
It's best practice to link your project using the
$(SRCROOT) macro so that if you move your project, or work on it with others using a remote repo, it will still work.
$(SRCROOT) can be thought of as the directory that contains your .xcodeproj file. It might look like this:
Step 3: Add Objective-C Header -- .h
.h file and name it
Step 4: Build your Objective-C Class
Step 5: Add Class to Bridging-Header
Step 6: Use your Object
No need to import explicitly, that's what the bridging header is for.
Using Swift Classes in Objective-C
Step 1: Create New Swift Class
.swift file to your project, and name it
Step 2: Import Swift Files to ObjC Class
<#YourProjectName#>-Swift.h should already be created automatically in your project, even if you can not see it.
Step 3: Use your class
1. CodeCompletion wasn't behaving as accurately as I'd like it to. On my system, running a quick build w/ "cmd + r" seemed to help Swift find some of the Objc code and vice versa.
2. If you add
.swift file to an older project and get error:
dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib, try completely restarting Xcode.
3. While it was originally possible to use pure Swift classes in Objective-C by using the
@objc prefix, after Swift 2.0, this is no longer possible. See edit history for original explanation. If this functionality is reenabled in future Swift versions, the answer will be updated accordingly.