顯示具有 Objective-C 標籤的文章。 顯示所有文章
顯示具有 Objective-C 標籤的文章。 顯示所有文章

2015年7月13日 星期一

[Swift] Using Swift Protocol in Objective-C

I have a ListView that is populated with detected device information when my scanning service has successfully scanned nearby devices. My scanning service is in Objective C and my App is in Swift, so I will have to use Swift protocol in Objective C functions.

The goal is simple: when device is found, notify the ListView controller. The ListView controller will then retrieve detected device information and then populate the ListView. Note that in the following snippet I have omitted how to populate data into ListView

If you follow the following steps you should have no problem using Swift protocol in Objective C files.

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"