我试图让一个 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。
这里有什么问题?