我正在尝试将我的应用程序从 Objective C 迁移到 swift。 我有几个 Objective C 类别。因为 Swift 有“扩展”,所以我创建了它。但不知何故,我无法从现有的 Objective C 中调用它。
下面的代码编译错误
No visible @interface for 'NSString' declares the selector 'myCategory'
扩展类
import Foundation
extension String {
func myCategory() -> String {
return "I am From Swift";
}
}
我的 View Controller
#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
它如何与 Swift 类一起工作? 我还为上述扩展文件创建了桥接头文件。
编辑: 我试过将其设置为“公开”,但它不起作用。
最佳答案
你的想法是对的,但是 Swift 的 String
和 Cocoa 的 NSString
是两种不同的类型。你没有意识到这一点的原因是,多亏了一些魔法,Swift 很乐意调用 String
上的 NSString
方法,让你的生活更轻松。在 NSString
而不是 String
上进行扩展,它应该在两种情况下都能工作。
关于ios - 为 Swift 和 Objective-C 类定义扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37336045/