我开始学习 Swift,并且一直在关注 YouTube 上非常棒的斯坦福大学视频讲座。如果您有兴趣或它有帮助(尽管不需要理解我的问题),这里有一个链接:
Developing iOS 8 Apps with Swift - 2. More Xcode and Swift, MVC
在听完讲座后,我发现(据我所知)我的代码与视频中的代码完全相同,但在我的系统上我遇到了编译器错误。经过大量的试验和错误后,我设法将我的代码减少到两个示例,其中一个生成错误,另一个生成错误或不生成错误,但我不知道究竟是什么导致了错误或如何解决它。
产生错误的代码是:
import UIKit
class BugViewController: UIViewController
{
func perform(operation: (Double) -> Double) {
}
func perform(operation: (Double, Double) -> Double) {
}
}
这会产生以下编译器错误:
Method 'perform' with Objective-C selector 'perform: ' conflicts with previous declaration with the same Objective-C selector
通过简单地删除 UIViewController 的子类,代码编译:
import UIKit
class BugViewController
{
func perform(operation: (Double) -> Double) {
}
func perform(operation: (Double, Double) -> Double) {
}
}
一些其他可能相关或不相关的信息:
我有一半希望这是编译器中的错误,否则这对我来说没有任何意义。非常感谢收到任何帮助!
最佳答案
我自己也在上斯坦福的类(class),我也在这里卡了很长时间,但经过一番搜索,我从这里找到了一些东西:Xcode release notes它提到了以下内容:
Swift 1.2 is strict about checking type-based overloading of @objc methods and initializers, something not supported by Objective-C.
// Has the Objective-C selector "performOperation:". func performOperation(op: NSOperation) { /* do something */ } // Also has the selector "performOperation:". func performOperation(fn: () -> Void) { self.performOperation(NSBlockOperation(block: fn)) }This code would work when invoked from Swift, but could easily crash if invoked from Objective-C. To solve this problem, use a type that is not supported by Objective-C to prevent the Swift compiler from exposing the member to the Objective-C runtime:
- If it makes sense, mark the member as private to disable inference of @objc.
- Otherwise, use a dummy parameter with a default value, for example: _ nonobjc: () = (). (19826275)
Overrides of methods exposed to Objective-C in private subclasses are not inferred to be @objc, causing the Swift compiler to crash. Explicitly add the @objc attribute to any such overriding methods. (19935352)
Symbols from SDKs are not available when using Open Quickly in a project or workspace that uses Swift. (20349540)
我所做的只是在覆盖方法前添加“private”,如下所示:
private func performOperation(operation: Double -> Double) {
if operandStack.count >= 1 {
displayValue = operation(operandStack.removeLast())
enter()
}
}
关于swift - 编译器错误 : Method with Objective-C selector conflicts with previous declaration with the same Objective-C selector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29457720/