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
  • 30,595
  • 22
  • 143
  • 179
Yatendra
  • 1,262
  • 1
  • 19
  • 31

1 Answers1

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,541
  • 2
  • 38
  • 65