Yatendra
Yatendra

Reputation: 1306

How to access Swift class from Objective-C class?

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];

Upvotes: 0

Views: 826

Answers (2)

Sheetal Shinde
Sheetal Shinde

Reputation: 529

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

Upvotes: 0

arturdev
arturdev

Reputation: 11039

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>

Upvotes: 0

Related Questions