【问题标题】:Overriding func in Swift [duplicate]在 Swift 中覆盖 func [重复]
【发布时间】:2015-06-29 08:19:25
【问题描述】:

我正在学习 Swift,我正在学习 Paul Hegarty 的教程,内容是如何使用波兰逆表示法构建计算器。代码如下所示:

@IBAction func operate(sender: UIButton) {
    let operation = sender.currentTitle!
    if userIsEnteringData{
        enter()
    }
    switch operation {
    case "×": performOperation {$0 * $1}
    case "÷": performOperation {$1 / $0}
    case "+": performOperation {$0 + $1}
    case "−": performOperation {$1 - $0}
    case "√": performOperation {sqrt($0)}
    case "sin": performOperation {sin($0)}
    case "cos": performOperation {cos($0)}
    case "π": performOperation{$0 * M_PI}
    default: break
    }

}

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()

    }
}

xCode 编译器不喜欢 performOperation 函数的第二个实例,并报告它之前已经定义过。它报告的错误是:

Method 'performOperation' with Objective-C selector 'performOperation:' conflicts with previous declaration with the same Objective-C selector

我的代码有什么问题?

【问题讨论】:

  • 你的类是 NSObject 的子类吗?
  • @flashadvanced 类定义如下: class ViewController: UIViewController { .... } 我猜 UIViewerController 继承自 UIResponder : NSObject

标签: swift functional-programming


【解决方案1】:

我不知道您的类声明,但在这种情况下最可能的问题是您继承自 @objc 类。 Objective-C 不支持方法重载,但 Swift 支持。因此,如果可以的话,您不应该从 @objc 类继承,或者您可以只使用不同的方法名称。

参考你可以阅读this post

【讨论】:

  • 感谢您指点我参考。阅读帖子后,我更好地理解了问题和可能的解决方法。问题的路径是我的班级有点打破了 MVC 模式,因为我混合了“视图”和“模型”。通过将“模型”代码拆分为一个不继承自 UIControl 的单独类,我应该能够拥有两个版本的 performOperation 函数一个(Double,Double)-> Double 和一个 Double -> Double。
  • 如果我的帖子回答了您的问题,您可以点击勾选接受它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 2012-02-16
  • 1970-01-01
  • 2016-01-28
  • 2013-12-12
  • 2010-11-12
相关资源
最近更新 更多