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!

3 Answers 3

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 ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

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 answer updated. that was a slip of the tongue!
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 .

Comments

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?

2 Comments

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'
Yes, thank you. I marked another answer as correct. I had to instantiate a ViewController before I could call a function on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.