无法在Obj-C类中找到Swift协议声明

7

我已经在Swift中创建了一个Class,并且我正在使用该类及其协议在启用Obj-C的项目中,但是在编译我的项目时出现以下错误。

无法找到“SpeechRecognizerDelegate”的协议声明;您是否指的是“SFSpeechRecognizerDelegate”?

有人可以指导我如何在我的Obj-C类中使用Swift类协议吗?

这是我的Swift代码:

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


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

}

Objective-C中的协议使用:

#import "ARBot-Swift.h"

@interface ChatScreenViewController : JSQMessagesViewController <SpeechRecognizerDelegate>

如果需要更多信息,请告诉我。谢谢您提前的帮助。
5个回答

10

在 Swift 中:

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

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

在 Objective-C 的 headerFile.h 文件中

@protocol YOURSwiftDelegate;

@interface YOURController : UIViewController < YOURSwiftDelegate >

在 Objective-C Implementation.m 文件中

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

1
这是正确的答案。关键是在您的Objective C代码中添加@protocol YOURSwiftDelegate;行。之后,下一个错误将要求您定义缺失的函数。 - look

4

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

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

在项目设置内创建一个 Swift 模块,然后使用它。你可以在这里找到完整的博客以了解混合语言编程。
接着,在 Objective C 类中使用 Protocol,
我们需要在 Objective C 文件中添加 protocol -
#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
}

1
你说的“add protocol inside”是什么意思?我用“confirm protocol”做同样的事情,但是编译器报错了。 - CodeChanger
你需要为协议确认添加协议方法。你做完了吗?@CodeChanger - Anand Nimje
你是否像这样使用你的 protocol@objc protocol SpeechRecognizerDelegate - Anand Nimje

2

在我按照(导入头文件 + 协议 Objc 注释)的步骤后,出现了类似的问题。在使用来自Objective C头文件的Swift代码时,会收到警告。只需将其导入实现文件 .m 中即可解决。


1
在你的协议中添加@objc属性:
@objc protocol SpeechRecognizerDelegate : class  {
    //...
}

0

使用前向声明在Objective-C头文件中包含Swift类

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接