Overriding func in Swift [duplicate]

时光总嘲笑我的痴心妄想 提交于 2019-12-23 03:06:58

问题


I am learning Swift and I am following a tutorial from Paul Hegarty on how to build a calculator using Polish Inverse Notation. The code looks like this:

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

    }
}

The xCode compiler does not like the second instance of the performOperation function and reports that it has already been defined previously. The error it reports is:

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

What is wrong with my code?


回答1:


I am not aware of your class declaration but the most possible issue in this case is that you inherit from an @objc class. Objective-C does not support method overloading but Swift does. So either you shouldn't be inheriting from am @objc class if you can or you can just use different method names.

For reference you can read this post



来源:https://stackoverflow.com/questions/29784619/overriding-func-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!