0

I have a project that is a cross of Swift and Objective-C using a bridging-header.

In my main ViewController.swift file, outside of the class declaration, I have this code:

var mainView = ViewController()

In other views that I segue to, I can use this to call a function to run back on the main ViewController by using mainView.runFunction()

How can I call this function in an Objective-C .m implementation file?

Thanks!

RanLearns
  • 4,086
  • 5
  • 44
  • 81

3 Answers3

1

First of all for using swift in objective-c you need to import TargetName-Swift.h. Note that it's the target name.

For more information look at this.

You can achieve what you want in this way:

ViewController *mainView = [[UIViewController alloc] init];
[mainView runFunction];

Also you should declare your runFunction with @objc to use it in objective-c like below:

@objc func runFunction {
    // what you want to do ...
}
Arash Etemad
  • 1,827
  • 1
  • 13
  • 29
  • 1
    Thanks for answering. Even though I have a ViewController.swift file and added `@objc` to its class definition, your code pops up the error "Unknown receiver ViewController" - if I add the `#import "project-Swift.h"` then the view controller is recognized in the first line of your code, but the second line shows error `"No visible @interface for 'UIViewController' declares the selector 'runFunction'"` – RanLearns Jan 01 '19 at 04:30
  • @RanLearns answer updated. that was a slip of the tongue! – Arash Etemad Jan 01 '19 at 08:22
0

Follow this apple article and done : Load Swift in Objective-C. Or I already did is a "trick" using "@objc" key, look at this little explanation: What is @objc attribute, one easy way is just create a helper function that will be visible to your Objective-c class and done like:

@objc func retrieveMainView() -> UIViewController { return MyViewController() }

And you call this from your objective-c class, maybe you need to anotate your swift class with @objc, look at this two reference and you will get the idea and figure out for sure .

Felipe Florencio
  • 325
  • 2
  • 10
0

In your Objective file i.e. .m file add below import statement:

import "<ProjectName>-Swift.h"

For example your project name is MyProject, so import statement would look like:

import "MyProject-Swift.h"

And call your function like: [mainView runFunction];

I hope this will help. You can also refer one of my answer: How can I import Swift code to Objective-C?

Dheeraj D
  • 4,386
  • 4
  • 20
  • 34
  • Thanks for answering. I believe my import statement is correct (no errors upon running) but the [mainView runFunction]; is erroring as `Use of undeclared identifier 'mainView'` – RanLearns Jan 01 '19 at 04:38
  • Yes, thank you. I marked another answer as correct. I had to instantiate a ViewController before I could call a function on it. – RanLearns Jan 04 '19 at 13:20