【问题标题】:Overloaded functions in swift error [duplicate]swift错误中的重载函数[重复]
【发布时间】:2015-11-06 16:23:24
【问题描述】:

我是 swift 新手,以下代码有错误。我有一个带有两个不同参数的函数。 Xcode(版本 6)在第二个定义中给出了一个错误,其中一个参数是一个接受一个值的函数。这里是代码:

func performOperation(operation: (Double, Double) -> Double) {
    if(operandStack.count >= 2){
        displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
        enter()
    }
}

func performOperation(operation: Double -> Double){
    if(operandStack.count >= 1){
        displayValue = operation(operandStack.removeLast())
        enter()
    }

}

【问题讨论】:

  • 请显示您遇到的错误...
  • 显示错误,因为这个重载是合法的,没有任何问题
  • 使用 Objective-C 选择器 'performOperator:' 的方法 performOperation 与之前的声明冲突
  • 我有两次调用函数 performOperation -
  • performOperation{ $1 - $0 } performOperation{ sqrt($0) }

标签: ios xcode swift


【解决方案1】:

更新:
另一种解决方案是在方法定义前添加privateSource):

private func performOperation(operation: (Double, Double) -> Double) {
    if(operandStack.count >= 2){
        displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
        enter()
    }
}

private func performOperation(operation: Double -> Double){
    if(operandStack.count >= 1){
        displayValue = operation(operandStack.removeLast())
        enter()
    }

}

原答案:
看起来您的方法是在从某些 Objective-C 类继承的类中定义的,例如:

class TestClass : NSObject {  
    func test(a : String) {}
    func test(a : UInt) {}
}

编译器会产生这样的错误:

方法 'test' 与 Objective-C 选择器 'test:' 冲突 具有相同 Objective-C 选择器的先前声明。

要解决您需要避免从 Objective-C 类继承的问题:

class TestClass {  
    func test(a : String) {}
    func test(a : UInt) {}
}

此变体将正常工作。

问题在于 Objective-C 不支持方法重载,但 Swift 支持。这就是为什么你需要创建纯 Swift 类。

【讨论】:

  • 这个函数在ViewController类中定义:UIViewController
  • @sanjivsoni UIViewController 是 ObjC 类。考虑创建单独的 Swift 类并在那里定义这些函数。然后你就可以在 ViewController 中使用该类:UIViewController 类。
  • @sanjivsoni 在回答中查看我的更新。
猜你喜欢
  • 2015-12-17
  • 1970-01-01
  • 2018-07-23
  • 2015-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多