2

我试图让一个 Objective-C 类采用一个用 Swift 文件编写的协议。在某种程度上,我让 Swift 与 Objective-C 互操作。(我可以从 Swift 构建我的 Objective-C 类)。

我有:

@objc public protocol FooProtocol {
    func foobar()
}

然后,我的 Objective-C 文件:

#import <UIKit/UIKit.h>
#import "SwiftObjcProtocolTest-Bridging-Header.h"

@protocol FooProtocol
@end

@interface ObjClass1 : NSObject <FooProtocol>

-(void)foobar;

@end

并暗示:

#import "ObjClass1.h"

@implementation ObjClass1

- (void)foobar {
    NSLog(@"foobar protocol function called");
}

@end

但是当我给 Swift(主要在应用程序委托中这样做)一个委托属性并尝试将 Objective-C 对象分配给它时:

var delegate: FooProtocol?
....
delegate = objcInstance
delegate?.foobar()

它失败了:

无法将类型“ObjClass1”的值分配给类型“FooProtocol?”。

我试过用它来强制它,as! FooProtocol但这会导致 SIGABRT。

这里有什么问题?

4

1 回答 1

0

为了让这个工作,我发现:

  1. 确保将您的 Swift 代码导入到 Objective-C(参见此处)。将其导入ObjClass1.m.
  2. 您对协议的前向声明FooProtocol应如下所示:

    @protocol FooProtocol;
    

代替:

    @protocol FooProtocol
    @end

注意:虽然这对我有用,但可能有更好的解决方案,因为我收到警告ObjClass1.hCannot find protocol definition for 'FooProtocol'.

于 2017-05-28T03:22:36.950 回答