如何为具有引用返回类型的objc协议定义/声明swift方法?

时间:2015-08-12 03:03:43

标签: objective-c swift

我创建了一个objc协议:

@protocol CGEventTapHandler
  - (CGEventRef)onCGEvent:(CGEventTapProxy)proxy type:(CGEventType)type event:(CGEventRef)event;
@end

然后在我的快速课程中,我得到了签名:

func onCGEvent(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent!) -> Unmanaged<CGEvent>!

现在让人感到困惑。我收到了一些错误。

第一个错误是:

...: Protocol requires function 'onCGEvent(_:type:event:)' with type '(CGEventTapProxy, type: CGEventType, event: CGEvent!) -> Unmanaged<CGEvent>!'

...: Candidate is not '@objc', but protocol requires it

所以我添加&#39; @ objc&#39;到签名然后我得到:

...: Method cannot be marked @objc because its result type cannot be represented in Objective-C

根据要求编辑:

class ViewController: NSViewController, CGEventTapHandler {
  func onCGEvent(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent!) -> Unmanaged<CGEvent>! {
  }
}

1 个答案:

答案 0 :(得分:0)

不完全确定您的错误在哪里,所以这是一个有效的教程。 从一个针对 OS X 的全新的 Swift 项目开始。

创建Objective-C协议

文件名: CGEventTapHandler.h 。当提示您创建桥接标题时,请批准。

#import <CoreGraphics/CoreGraphics.h>
@protocol CGEventTapHandler
- (CGEventRef)onCGEvent:(CGEventTapProxy)proxy type:(CGEventType)type event:(CGEventRef)event;
@end

注册协议

文件名: ...- Bridging-Header

#import "CGEventTapHandler.h"

采用协议

在您的客户端类中,采用CGEventTapHandler

import Cocoa
class ViewController: NSViewController, CGEventTapHandler {
    func onCGEvent(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent!) -> Unmanaged<CGEvent>! {
        return nil
    }
}

编译,链接,构建和运行。没有警告,没有错误。