2015年7月9日 星期四

[Swift] Calling Swift Function in Objective-C Class

I have a service written in Objective-C and my App in Swift. Here's how to call Swift Functions from Objective-C files.

Step 1:
In your Objective-C .m file where you want to add the Swift function, make sure you import the Swift Header

1
#import "{Poduct Module Name}-Swift.h"

You can check your Product Module Name in the project Build Settings. For Example if your Product Module Name is "Hello_World", you will need to #import "Hello_World-Swift.h"

Step 2 Sample Swift Code:

1
2
3
4
5
@objc class testClass: UITableViewController {
    func printTest(){
        println("Hello From Swift") 
    }
}

Step 3, Call Swift Class in Objective-C method like so:
1
2
3
4
5
6
- (void) actionCompleted {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"actionCompleted" object:self];
    
    testClass *daTestClass = [[testClass alloc] init];
    [daTestClass printTest];
}


You cannot import {PMN}-Swift.h into Objective C Header. To do that you must forward declaration as  mentioned here under "Referencing a Swift Class or Protocol in an Objective-C Header"

沒有留言:

張貼留言