0

I want to access swift class(variables and methods) in my objC class.

I have created a YourProjectName-Swift.h file.

  1. set "Defines Module" to YES in build setting
  2. check Product Module Name the same with my swift file name.
  3. set Install Objective-C Compatibility Header to YES
  4. set Objective-C Generated Interface Header : YourProjectName-Swift.h
  5. then Import Swift interface header in *.m file.
#import "YourProjectName-Swift.h"

My swift class is:

@objc public class MySwiftClass: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        addBehavior()
    }

    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        addBehavior()
    }

    func addBehavior() {
        print("Add all the behavior here")
    }
}

How can I access this class from an Objective-C file?

I tried to initiate my swift class object with the below, but it's not working.

MySwiftClass *swift = [[MySwiftClass alloc] init];
pkamb
  • 33,281
  • 23
  • 160
  • 191
Yatendra
  • 1,310
  • 1
  • 18
  • 31

2 Answers2

0

You shouldn't create YourProjectName-Swift.h file. It will be generated automatically for you!

Just import YourProjectName-Swift.h in your ObjC class where you want to access swift class, and use it.

Considerations:

If your target name contains spaces, replace them with underscores (e.g. Your Project Name becomes Your_Project_Name-Swift.h)

If your target is a framework, you need to import <YourProjectName/YourProjectName-Swift.h>

arturdev
  • 10,884
  • 2
  • 39
  • 67
0

Add '@class MySwiftClass' in '.h' file of objective C

Sheetal Shinde
  • 489
  • 5
  • 7