objective-c - 无法使用 Swift 协议(protocol)将符合协议(protocol)的 Objective-C 类分配给属性

标签 objective-c swift protocols bridging-header objc-bridging-header

我正在尝试让 Objective-C 类采用用 Swift 文件编写的协议(protocol)。我在某种程度上让 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(主要是在应用程序委托(delegate)中这样做)一个委托(delegate)属性并尝试将 Objective-C 对象分配给它时:

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

它失败了:

cannot assign value of type 'ObjClass1' to type 'FooProtocol?'.

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

这里有什么问题?

最佳答案

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

  1. 确保将您的 Swift 代码导入 Objective-C (see here)。将其导入 ObjClass1.m
  2. 协议(protocol) FooProtocol 的前向声明应该如下所示:

    @protocol FooProtocol;
    

代替:

    @protocol FooProtocol
    @end

注意:虽然这对我有用,但可能有更好的解决方案,因为我在 ObjClass1.h 中收到警告说 Cannot find protocol definition对于“FooProtocol”

关于objective-c - 无法使用 Swift 协议(protocol)将符合协议(protocol)的 Objective-C 类分配给属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44223186/

相关文章:

ios - iPad 应用程序在方向更改时崩溃

ios - 无法在 UIWebView 中播放 Youtube 视频(iOS、Swift)

swift - 是否可以通过在 iOS 中使用具有质量设置的 jpeg 编码器来记录并保存到文件?

ios - 协议(protocol)委托(delegate)未按预期传递数据 [Swift5]

javascript - Chrome 调试协议(protocol) : Create local storage value

protocols - 串行协议(protocol)中的错误检测/纠正/恢复

ios - 如何使用最新的 iOS SDK 在 Pinterest 中分享图片

ios - ObjC、Facebook 页面 - 发布新闻提要有效,但发布照片无效

c# - 如何使用 QuickFIX 引擎发送简单的 QuoteRequest 消息?

iphone - NSDateFormatter 模拟器上的日期不正确,设备上的日期正确