swap swap - 5 months ago 26x
iOS Question

Defining an extension for both the Swift and Objective-C classes

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 ()


@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.


And how it will be work with Swift class also?
I have created Bridging header file also for above extension file.

I have tried making "public" but its not working.


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.