how to import swift class in objective-c class?

Asked on 09/19/2024

1 search

To import a Swift class into an Objective-C class, you need to use a bridging header. Here’s a step-by-step guide:

  1. Create a Bridging Header: If your project doesn't already have a bridging header, Xcode will prompt you to create one when you add a Swift file to an Objective-C project. If it doesn't, you can manually create a header file and name it something like ProjectName-Bridging-Header.h.

  2. Import Swift Code: In your bridging header file, import the Swift module using the @import directive. For example, if your Swift class is part of a module named MySwiftModule, you would add:

    @import MySwiftModule;
    
  3. Access Swift Classes: Once the bridging header is set up, you can use your Swift classes in Objective-C files as if they were Objective-C classes. Make sure your Swift classes are marked with @objc or inherit from NSObject if you need to expose them to Objective-C.

  4. Build Settings: Ensure that your project's build settings are configured to use the bridging header. In the "Build Settings" tab, search for "Objective-C Bridging Header" and set the path to your bridging header file.

For more detailed information on interoperability between Swift and Objective-C, you might find the session Demystify explicitly built modules helpful, as it discusses how modules and imports work in both languages.