【问题标题】:Defining an extension for both the Swift and Objective-C classes为 Swift 和 Objective-C 类定义扩展
【发布时间】:2016-05-20 00:14:12
【问题描述】:

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

        }


    } 

我的视图控制器

#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 类一起工作? 我还为上述扩展文件创建了桥接头文件。

编辑: 我已经尝试过“公开”,但它不起作用。

【问题讨论】:

  • 我已经尝试过但没有成功

标签: ios objective-c swift


【解决方案1】:

你的想法是对的,但是 Swift 的 String 和 Cocoa 的 NSString 是两种不同的类型。您不知道这一点的原因是,由于某种魔法,Swift 很乐意在 String 上调用 NSString 方法,让您的生活更轻松。在 NSString 而不是 String 上制作您的扩展程序,它应该在这两种情况下都可以工作。

【讨论】:

    猜你喜欢
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多