Swift classes not found in Objective-C project
Asked Answered
R

2

6

I am working on an iOS project developed using Objective-C. I need to integrate some Swift files in it. So, did following:

  1. Added a new Swift file named "temp", so that MyProject-Bridging-Header.h is added by my Xcode IDE (Version 9.1).
  2. Added the Swift files, which I want to use, to the project.
  3. Changed target setting Defines Module to YES.
  4. Similarly, Product Module Name is set to "MyProject".
  5. I can see the MyProject-swift.h a file name for the setting "Objective-C Generated Interface Header Name".
  6. Added import statement for MyProject-swift.h in one of my Objective-C .m files and was able to build the project successfully.
  7. I checked in Finder that MyProject-swift.h was created.
  8. Ensured the @obj prefix in the Swift classes declaration.

Still, when I try to use any of the Swift classes, then I get compile time error "User of undeclared identifier".

What can be the reason for the issue? Am I missing something?

[update Xcode 14] By default the PRODUCT_MODULE_NAME is set to XXX-Swift.h < Swift with an S capital.

Rollo answered 28/12, 2017 at 14:27 Comment(0)
R
7

Figured it out...

I was missing the forward declaration of the Swift class in my Objective-C class. All I needed to do was to add following statement before the interface declaration in the .h file.

@class MySwiftClassName;

Once the statement was added, it's building successfully.

Rollo answered 29/12, 2017 at 2:23 Comment(0)
T
0

[Xcode 14 update]

To get Swift classes exposed to Objective-C

Process:

  1. Inherit classes from NSObject
  2. Give attribute @objcMembers directly to Swift classes or selectively @objc to expected classes members.
  3. In the headers of ObjC classes where you want to use Swift classes add the swift class declarations @class SwiftClassXXX;
  4. accordingly, in the .m files of ObjC classes where you want to use Swift classes, #import a header that will be automatically generated by the compiler. If your project is named MyProject, the automatic header will be MyProject-Swift.h (S capital).
  5. Use your Swift class(es) in your .m's

You can change or check the MyProject-Swift.h automatic header name, checking the PRODUCT_MODULE_NAME in the build settings — and change it if you want.

Turgot answered 22/3, 2023 at 8:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.