Reputation: 1878
I am trying to migrate my application to swift from Objective C. I was having couple of Objective C categories. Since Swift is having "Extensions", I have created it. But some how , I am not able to call it from existing Objective C.
Below code gives compilation error
No visible @interface for 'NSString' declares the selector 'myCategory'
Extension class
import Foundation
extension String {
func myCategory() -> String {
return "I am From Swift";
}
}
My ViewController
#import <TestProject-Swift.h>
@interface TestViewController ()
@end
@implementation TestViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *str = @"Testing";
NSLog(@"Here is result %@", [str myCategory]);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
And how it will be work with Swift class also? I have created Bridging header file also for above extension file.
EDIT: I have tried making "public" but its not working.
Upvotes: 0
Views: 79
Reputation: 14824
You have the right idea, but Swift's String
and Cocoa's NSString
are two different types. The reason you aren't aware of this is that thanks to some magic, Swift is happy to call NSString
methods on String
to make your life easier. Make your extension on NSString
instead of String
and it should work in both contexts.
Upvotes: 1