简体   繁体   English

将Swift Initialisers桥接到Objective C

[英]Bridging Swift Initialisers to Objective C

I'm attempting to slowly migrate an Objective C app over to Swift and have started to create new classes - 我正在尝试将Objective C应用程序缓慢迁移到Swift并开始创建新类 -

public class MapsAPI : NSObject {

    let delegate: MapsAPIResponseDelegate

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

}

Now in my Objective C .m file I've declared #import MyTarget-Swift.h and in my .h I've added @class MapsAPI which all seems fine however I'm not sure what the Objective C initialisation code should look like. 现在在我的Objective C .m文件中,我已经声明了#import MyTarget-Swift.h而在我的.h我添加了@class MapsAPI ,这一切看起来都不错但是我不确定Objective C初始化代码应该是什么样的。 I've tried - 我试过了 -

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

But that errors with - 但那个错误 -

No visible @interface for 'MapsAPI' declares the selector 'initWithManagerWithDelegate:' 'MapsAPI'没有可见的@interface声明选择器'initWithManagerWithDelegate:'

I've tried looking at the definition of my MyTarget-Swift.h but all that shows is - 我已经尝试过查看MyTarget-Swift.h的定义,但所有显示的是 -

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

Is there something I'm doing wrong here? 我有什么问题吗?

You may choose to add @objcMembers to your class declaration: 您可以选择将@objcMembers添加到您的类声明中:

public class @objcMembers MapsAPI : NSObject {

    let delegate: MapsAPIResponseDelegate

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

Alternatively (or additionally... who am I to judge) you can mark your initializer as being exposed to Objective-C 或者(或者另外......我要判断谁)你可以将初始化程序标记为暴露于Objective-C

public class MapsAPI : NSObject {

    let delegate: MapsAPIResponseDelegate

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

And if you want to, you can also explicitly define the Objective-C selector used: 如果您愿意,还可以显式定义使用的Objective-C选择器:

public class MapsAPI : NSObject {

    let delegate: MapsAPIResponseDelegate

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM