我正在尝试让 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。
这里有什么问题?
最佳答案
为了让这个工作正常,我发现:
- 确保将您的 Swift 代码导入 Objective-C (see here)。将其导入
ObjClass1.m
。 协议(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/