ios - 为 Swift 和 Objective-C 类定义扩展

标签 ios objective-c swift

我正在尝试将我的应用程序从 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/

相关文章:

swift - 直接赋值UnsafePointer

ios - 您可以自定义 SwiftUI 上下文菜单的激活突出显示颜色吗?

ios - Swift ios 从任何地方展开到根 ViewController 选项卡

iphone - 上下文绘图+分页

ios - 事件指示器 iOS

ios - 读取自定义框架中的 info.plist

ios - 将 NSOperation 的结果传递给另一个 NSOperation

ios - Apple 开发者帐户作为个人和公司/组织之间的区别

ios - UICollectionView补充 View 如何正确插入或删除

ios - [UINavigationController保留] : message sent to deallocated instance