将Swift初始化程序桥接到目标C

时间:2018-04-09 20:18:10

标签: objective-c swift xcode

我正在尝试将Objective C应用程序缓慢迁移到Swift并开始创建新类 -

public class MapsAPI : NSObject {

    let delegate: MapsAPIResponseDelegate

    public init(managerWithDelegate delegate: MapsAPIResponseDelegate) {
        self.delegate = delegate
    }

}

现在,在我的Objective C .m文件中,我已声明#import MyTarget-Swift.h,而在.h我已添加@class MapsAPI这一切似乎都很好但是我不确定Objective C初始化代码应该是什么样子。我试过了 -

MapsAPI *api = [[MapsAPI alloc] initWithManagerWithDelegate: self];

但是错误 -

  

'MapsAPI'没有可见的@interface声明选择器   'initWithManagerWithDelegate:'

我已经尝试查看我的MyTarget-Swift.h的定义,但所有显示的都是 -

SWIFT_CLASS("_TtC4What7MapsAPI")
@interface MapsAPI : NSObject
- (nonnull instancetype)init SWIFT_UNAVAILABLE;
@end

我在这里做错了吗?

1 个答案:

答案 0 :(得分:3)

您可以选择将@objcMembers添加到您的班级声明中:

public class @objcMembers MapsAPI : NSObject {

    let delegate: MapsAPIResponseDelegate

    public init(managerWithDelegate delegate: MapsAPIResponseDelegate) {
        self.delegate = delegate
    }
}

或者(或者另外......我要判断谁)你可以将初始化程序标记为暴露于Objective-C

public class MapsAPI : NSObject {

    let delegate: MapsAPIResponseDelegate

    @objc public init(managerWithDelegate delegate: MapsAPIResponseDelegate) {
        self.delegate = delegate
    }
}

如果您愿意,还可以明确定义使用的Objective-C选择器:

public class MapsAPI : NSObject {

    let delegate: MapsAPIResponseDelegate

    @objc(initManagerWithDelegate:)
    public init(managerWithDelegate delegate: MapsAPIResponseDelegate) {
        self.delegate = delegate
    }
}