1

When I execute Swift methods in Objective-C the code which is inside of that method does not run.

For example: I want to open a new view or enable a button.

Objective-C code:

Principal *myClass = [[Principal alloc] init];
[myClass getData];

Swift code:

func getData() {
    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let vc: UIViewController = storyboard.instantiateViewControllerWithIdentifier("MenuViewController") as UIViewController
    dispatch_async(dispatch_get_main_queue(), {
        self.presentViewController(vc, animated: true, completion: nil)
    })
}
Binarian
  • 12,296
  • 8
  • 53
  • 84
Ruben
  • 19
  • 4

2 Answers2

1

Make sure you use the @objc keyword to tag your Swift classes so they’re available to your ObjC ones.

import Foundation

@objc class TestClass {
class func new() -> TestClass {
    return TestClass()
}

func testFunction() {
    println("This function works")
}
}

And here’s the Objective-C client:

#import "AppDelegate.h"
#import "TestProject-Swift.h"
@implementation AppDelegate
 - (BOOL)application:(UIApplication *)application 
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    TestClass *instance = [TestClass new];
    [instance testFunction];
    return YES;
}
@end

The secret here is to import the name of the target in this case “TestProject” with the “-Swift.h” extension. Xcode builds this for you and hides it behind the scenes in the derived data. For the above example, mine was left at: DerivedData/TestProject-aqpeqeuqusyzdtcqddjdixoppyqn/Build/Intermediates/TestProject.build/Debug-iphoneos/TestProject.build/DerivedSources/TestProject-Swift.h

Josué H.
  • 1,171
  • 3
  • 15
  • 35
0

You need to create a header (.h file) into your Project and import all classes you needed.

Your header file looks like.

#ifndef ProjectName_Bridging_Header_h
#define ProjectName_Bridging_Header_h

#import "Principal.h"

Afer that in your Build Settings, you need to be set the header file name into Objective-C Bridging Header

Like this. enter image description here

Josué H.
  • 1,171
  • 3
  • 15
  • 35