在 Obj-C class 中找不到 Swift 协议声明

Can not find Swift Protocol declaration in Obj-C class

我在 Swift 中的 Class 上创建了 class 及其协议,我在 Obj-C 启用的项目中使用了它,但是在编译我的项目时出现以下错误项目。

cannot find protocol declaration for 'SpeechRecognizerDelegate'; did you mean 'SFSpeechRecognizerDelegate'?

任何人都可以指导我如何在我的 Obj-C class.

中使用 Swift class 协议

这是我的 Swift 代码:

protocol SpeechRecognizerDelegate : class  {
    func speechRecognitionFinished(_ transcription:String)
    func speechRecognitionError(_ error:Error)
}


class SpeechRecognizer: NSObject, SFSpeechRecognizerDelegate {
    open weak var delegate: SpeechRecognizerDelegate?

}

Obj-C 中的协议使用:

#import "ARBot-Swift.h"

@interface ChatScreenViewController : JSQMessagesViewController <SpeechRecognizerDelegate>

如果需要更多信息,请告诉我。

提前致谢。

@objc 属性添加到您的协议:

@objc protocol SpeechRecognizerDelegate : class  {
    //...
}

在 Swift 文件中像这样定义 Swift 协议。

@objc protocol SpeechRecognizerDelegate: class{
  func speechRecognitionFinished(_ transcription:String)
  func speechRecognitionError(_ error:Error)
}

在您的项目设置中创建一个 Swift 模块,然后使用它。您可以找到 here complete blog 用于混合语言编码。

然后在里面使用Protocol Objective C class,

我们需要在 Objective C 文件中添加 协议 -

#import "ARBot-Swift.h"

@interface ChatScreenViewController : JSQMessagesViewController <SpeechRecognizerDelegate>

那么你需要遵守协议方法-

- (void)viewDidLoad {
    [super viewDidLoad];
    SpeechRecognizer * speechRecognizer = [[SpeechRecognizer alloc] init];
    speechRecognizer.delegate = self;
}


#pragma mark - Delegate Methods
-(void)speechRecognitionFinished:(NSString *) transcription{
   //Do something here
}

-(void)speechRecognitionError:(NSError *) error{
   //Do something here
}

我在关注之后遇到了类似的问题(导入 header + 协议上的 Objc 注释)。我在使用 Objective C header 中的 Swift 代码时收到警告。通过仅导入到实现 .m 文件中解决。

在Swift:

@objc public protocol YOURSwiftDelegate {
    func viewReceiptPhoto()
    func amountPicked(selected: Int)
}

class YourClass: NSObject {
    weak var delegat: YOURSwiftDelegate?
}

在Objective-CheaderFile.h

@protocol YOURSwiftDelegate;

@interface YOURController : UIViewController < YOURSwiftDelegate >

在Objective-CImplementation.m

SwiftObject * swiftObject = [SwiftObject alloc] init];
swiftObject.delegate = self

在 Objective-C Headers 中包含 Swift 类 使用前向声明

//MySwiftClass.swift
@objc protocol MySwiftProtocol {}
@objcMembers class MySwiftClass {}

// MyObjcClass.h
@class MySwiftClass;
@protocol MySwiftProtocol;

@interface MyObjcClass : NSObject
- (MySwiftClass *)returnSwiftClassInstance;
- (id <MySwiftProtocol>)returnInstanceAdoptingSwiftProtocol;
// ...
@end