I have an Objective-C project, and need hints on how to call a ViewController which is in Swift from another controller in Objective-C?
Asked
Active
Viewed 1.4k times
14
-
Create a `Objective-c Generated Interface Header` in your apps build setting. Now you can use this header to import you swift code in you Objective-C code and just use the view controller like you would any other. – rckoenes Aug 25 '15 at 10:08
-
How is posible to import a swift class? – rimtej Aug 25 '15 at 12:35
-
2This is NOT too broad. – RegularExpression Apr 29 '17 at 05:58
2 Answers
22
Apparently it's quite easy.
- You have to first make sure you're prepending your class declaration with
@objc
so that it's available to your Objective-C ones.
For example:
import Foundation
// Belongs to target 'TestProject'
@objc class SwiftController: UIViewController {
//... truncated
}
Now you simply have to import the name of your target (that the swift controller belongs to), appended with
'-Swift.h'
—exposing its interface—like so:#import "TestProject-Swift.h"

dangnabit
- 654
- 3
- 9
-
1no result, when i import a class #import "TestClass-Swift.h" doesen't find that class – rimtej Aug 25 '15 at 11:58
-
2You need to go in to your build settings and set the `Objective-c Generated Interface Header.` – rckoenes Aug 25 '15 at 12:40
-
-
2Make sure you're not importing the class and importing the **target** your class is in. So, if your class `TestClass` is in a project named `TestProject` (most likely with an auto-generated target called `TestProject`), then you would need to import `TestProject-Swift.h`. Remember, Swift files don't have headers. – dangnabit Aug 25 '15 at 21:25
-3
Create a new file "YourAppName-Bridging-Header.h" and in this file you have to import "Your objective-C view controller.h"
Go to Build setting and search for bridging header and link with your birdging-header path.
Now you are able to write code in swift as usual.

Sudhir
- 77
- 5
-
3I think OP is asking about accessing a Swift controller in an Objective C file. – dangnabit Aug 25 '15 at 10:17
-
1You can use this either you have to use swift controller in objective C file or objective C controller in swift file. – Sudhir Aug 25 '15 at 10:40
-
1Right, I see what you mean. Don't you have to prepend the Swift classes with `@objc`? – dangnabit Aug 25 '15 at 10:43
-
You shouldn't make the header anyway. It is automatically generated with the proper settings. Making it yourself invites a lot of user error. – Abandoned Cart Jul 29 '19 at 19:47