Mixing objective-c and swift: fatal error: use of unimplemented initializer 'init(target:action:)' for class

Mixing objective-c and swift: fatal error: use of unimplemented initializer 'init(target:action:)' for class

我的代码同时包含 objective-c 和 swift 类,到目前为止,一切都运行良好。但是,我添加了一个继承自 UIGestureRecognizer 的自定义手势识别器。我的代码可以编译,但是当我尝试 运行 时,出现以下错误:

    fatal error: use of unimplemented initializer 'init(target:action:)' for class 

我假设此错误源于 objective-c 和 swift 代码的混合,但我不知道如何解决它(除了用其中一种语言重写所有内容之外)。非常感谢您的帮助。

这很正常,因为

init(target target: AnyObject?,
     action action: Selector) 

documentation 中公开为指定的初始值设定项。 然而,奇怪的是,在 UIKit public 来源中它声明如下:

public init(target: AnyObject?, action: Selector) // designated initializer

结论:即使没有使用required关键字声明,您也必须为您的子类实现它。它可以简单地调用超级的init(target: AnyObject?, action: Selector)。 祝你好运。

扩展到 Arthur 提到的内容,这就是 Apple 为 init(coder aDecoder: NSCoder) 定义它的方式,使其成为子类实现所必需的。

The NSCoding protocol requires that conforming types implement the required initializer init(coder:). Classes that adopt NSCoding directly must implement this method. Subclasses of classes that adopt NSCoding that have one or more custom initializers or any properties without initial values must also implement this method. Xcode provides the following fix-it to serve as a placeholder implementation:

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented") 
}