Chances are, during migration from Objective-C to Swift, you would be doing it gradually. Therefore, you’ll spend a lot of time with a mixed-language project of Objective-C and Swift interoperating. A lot of confusion happens during this period of time just because of not knowing what to do to expose code written in these two languages to each other.
Swift Bridging Header
This article is focused on exposing Swift to Objective-C files, which can easily be done by adding the following import to any .m file you’d like to access the Swift code from:
You can read more on these here.
Introducing Precompiled Headers
However, the previous approach is mundane and can increase build time dramatically for each new Swift file added no matter how modest it is. Thankfully, there’s a solution for this, precompiling bridging headers or PCH for short. Check out this article for more context on what a PCH is and the reason behind its origin.
How can I use PCH files?
- In Xcode 10, go to New file > iOS:Other > PCH file.
- Name it something like (Project-Name)-Prefix.pch.
- In Build Settings > Apple Clang - Language, set Precompile Prefix Header to Yes.
- In the Prefix Header field, add the path to the PCH file you just created $(PROJECT_DIR)/$(PROJECT_NAME)/(Project-Name)-Prefix.pch.
- In there, you will need to import the automatically generate Swift Bridging Header which will be named something like (Project_Name)-Swift.h.
Note: You can search for the Swift bridging header using the Open Quickly command (Cmd+Shift+O) but you need to make sure that you build your project successfully with the Swift files in it.
PCH File Example
Here is an example of a PCH file produced by Swiftify:
What about the .h files?
Now all your Swift classes should be accessible in your .m files, but what about the .h files? For that, you will need to use forward declarations. Assuming that you want to use a Swift class called MySwiftClass, the forward declaration would look like the following:
This is to prevent Objective-C classes from inheriting from Swift classes.