swift - 覆盖 Swift 2 中的函数错误

标签 swift swift2

此代码在 XCode 6 中没有错误,但在 XCode 7 (Swift 2) 中出现此错误:

Method does not override any method from its superclass

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        /* Called when a touch begins */

}

当删除 override 字词时发生此错误:

Method 'touchesBegan(:withEvent:)' with Objective-C selector 'touchesBegan:withEvent:' conflicts with method 'touchesBegan(:withEvent:)' from superclass 'UIResponder' with the same Objective-C selector

最佳答案

您遇到第一个错误是因为 Cocoa Touch 的大部分内容都经过审核以支持 Objective-C 泛型,这意味着现在可以输入数组和集合等元素。因此,此方法的签名已更改,并且由于您编写的内容不再与此匹配,因此您会收到一条错误消息,说明您已将方法标记为 override 但它实际上不匹配父类(super class)中的任何方法。

然后当您删除 override 关键字时,您得到的错误是让您知道您创建的方法具有与真正的 touches begind 方法冲突的 Objective-C 选择器 (与 Swift 不同,Objective-C 不支持方法重载)。

底线是,在 Swift 2 中,您的触摸开始覆盖应该看起来像这样。

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    // stuff
}

有关 Objective-C 泛型对您的 Swift 代码意味着什么的更多信息,我建议您查看 Using Swift with Cocoa and Objective-C 预发行版中的轻量级泛型部分。 .截至目前第 33 和 34 页。

关于swift - 覆盖 Swift 2 中的函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30892254/

相关文章:

ios - Swift 语言 NSClassFromString

swift - 如何在 MacOS 中正确显示 xib 文件的模态视图?

swift - 这个例子中的 0xFFFFFFFF 是做什么的?

xcode - Swift 2.0 : Could not find overload. 需要解释

ios - 如何在 Swift 中向上滚动整个表格 View ?

json - 如何将 Swift 对象序列化或转换为 JSON?

ios - fatal error : unexpectedly found nil while unwrapping an Optional value error Swift

ios - 在 iOS 中使用 Swift 持久化 27000 个节点的 trie 数据树的方法是什么?

ios - 在 swift 2 中通过 segue 传递数据

swift - 无法在 Swift 中扩展闭包?