During the announcement of Swift, one of the first questions that came up in my mind was “Can I use Swift in my existing Objective-C projects?”. Indeed, the answer is Yes. Even though you will need to wait for a few more months until you can submit an app, written in Swift, to the App Stores, you can start experimenting with mixing up the two languages right now. All you will need is the latest version of Xcode 6.0 Beta.
The engineers at Apple have done a good job at automating the process making it easy for the developers. In order to use Swift in your Objective-C project, just add a .swift file to it. You can do so by selecting File->New->File.. (⌘N) At this point, you will get a prompt in Xcode, asking if you would like to create an Objective-C bridging header. This file is one of the two header files needed in oder for Swift to inter-operate with Objective-C. If you select the file, you will see that it is empty, except for a comment saying:
“Use this file to import your target’s public headers that you would like to expose to Swift.” This means that this header file should include all of the Objective-C header files you would like to be visible to the Swift part of your project. What is special about the bridging header file is its name. The file name is the name of your project, followed by “-Bridging-Header.h”. Xcode uses this convention in order to automate the process and save you some work. You are only responsible for listing the names of Objective-C headers in the file. The IDE will take care of the rest and you will be able to call your Objective-C methods inside Swift files.
What about the other way around? How can we make our Swift code visible in our Objective-C files? Xcode actually creates another header file for you. It also has a name convention: <Your Project Name> + “-Swift.h”. You cannot see this file in the project navigator. It is all generated and managed by Xcode. Your only job is to import it in any Objective-C file that you would like to have access to your Swift code.
These are the steps you will need to go trough in order to achieve interoperability between Objective-C and Swift. Of course these are only the basics but they should be enough for you to start playing around with the new language in an older (Pre-Swift) project. There are other more advanced topics to consider like language features differences and compatibility, and I will try to cover them in future posts. For now, try converting some of your older projects and start exploring Swift.