尝试重载功能,但Xcode显示错误

时间:2016-03-03 12:04:42

标签: xcode swift function overloading

我正在尝试使用Swift构建计算器。以下是我提出的代码。

对于这些开关案例:

case "×":performOperation {$0 * $1}
case "÷":performOperation {$1 / $0}
case "+":performOperation {$0 + $1}
case "−":performOperation {$1 - $0}

它接受两个参数函数:

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

对于这个开关案例:

case "√":performOperation {sqrt($0)}

我想出了一个只接受一个参数的重载函数:

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

但是,Xcode在一个参数函数旁边显示错误,说:

  

使用Objective-C选择器“performOperation”的方法“performOperation”   与之前的声明冲突与相同的Objective C选择器

这给我带来了很大的困惑。首先,我使用的是Swift,为什么选择Objective C?第二,我该如何解决这样的问题?请帮帮我!!

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var display: UILabel!

    var userIsInTheMiddleOfTypingANumber = false

    @IBAction func appendDigit(sender: UIButton) {
        let digit = sender.currentTitle!
        if userIsInTheMiddleOfTypingANumber {
            display.text = display.text! + digit
        } else {
            display.text = digit
            userIsInTheMiddleOfTypingANumber = true
        }
    }

    @IBAction func operate(sender: UIButton) {
        let operation = sender.currentTitle!
        if userIsInTheMiddleOfTypingANumber {
            enter()
        }
        switch operation {
        case "×":performOperation {$0 * $1}
        case "÷":performOperation {$1 / $0}
        case "+":performOperation {$0 + $1}
        case "−":performOperation {$1 - $0}
        case "√":performOperation {sqrt($0)}
        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()
        }
    }

    var operandStack = Array<Double>()

    @IBAction func enter() {
        userIsInTheMiddleOfTypingANumber = false
        operandStack.append(displayValue)
        print("operantStack = \(operandStack)")
    }

    var displayValue: Double {
        get {
            return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
        }
        set {
            display.text = "\(newValue)"
            userIsInTheMiddleOfTypingANumber = false
        }
    }

}

1 个答案:

答案 0 :(得分:0)

UIViewController继承自Objective C类型(UIViewController) - 即使您只使用swift。如果您创建了一个仅限swift的文件,您会发现可以使用方法名称重载。因此,您的performOperation之一需要更改。