Although Swift is widely used to develop iOS app today and you can even get an iOS developer job without knowing a bit of Objective-C, sometimes it’s still inevitable to face Objective-C, especially at work. You might be assigned the task of maintaining an old project or developing an app based on an old Objective-C project. Either situation could be quite challenging to a Swift programmer who barely knows Objective-C. So, a little knowledge of incorporating Swift into Objective-C might save you some trouble of dealing with it.
Import Swift Code File
Create a Bridging Header by Xcode
The first time you add a Swift file to an Objective-C project, this dialogue box will appear, asking if you would like to create a bridging header. Make sure you click Create Bridging Header, then Xcode will configure everything for you.
This prompt shows only once. If you miss it, don’t worry, you can still create the bridging header manually by adding a header file.
Create a Bridging Header Manually
- Add a header file: File >New > File > (Source) Header File. You should name the file
TargetName-Bridging-Header. Click “Create”, this header file will show on project navigator.
- Navigate to your target setting Target > Build Settings and search Swift Compiler — General. Objective-C Bridging Header under this section is supposed to have the path of your header file. Since you create a bridging header manually, you have to fill by yourself. If it resides in your project’s root folder, the path should be
ProjectName/TargetName-Bridging-Header. Alternatively, you can double click the empty value part, drag the header file and drop it in the box, just let Xcode fill the path for you.
If there’s no Swift Compiler section, this means you probably don’t have any swift file added to your project.
- Go to both Project and Target/Build Settings/All/Packaging, change the value of Defines Module from No to Yes.