来自斯坦福斯威夫特球场的斯威夫特计算器

时间:2015-08-13 09:31:00

标签: swift

我们从Stanford swift课程开始研究计算器,我们一直在调用方法performOperation,其中发生错误(使用局部变量" performOperation"在声明之前)。任何帮助或建议来解决问题将谢谢。谢谢

import UIKit

class ViewController: UIViewController {


@IBOutlet weak var display: UILabel!

var userIsInTheMiddleOfTypingNumber: Bool = false


@IBAction func appendDigit(sender: UIButton){

    let digit = sender.currentTitle!
    if userIsInTheMiddleOfTypingNumber {
        display.text = display.text! + digit
    }
    else {
        display.text = digit
        userIsInTheMiddleOfTypingNumber = true

    }
    //println("digit = \(digit)")
}

@IBAction func operate(sender: UIButton) {
    let operation = sender.currentTitle!
    if userIsInTheMiddleOfTypingNumber {
     enter()
    }
    switch operation {
    case"×": performOperation() { $0 * $1 }  - THIS IS THE CODE WHERE WE GOT ERROR
        //            case"÷":
//            case"+":
//            case"-":
    default: break

    }

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

var operandStack = Array<Double>()

@IBAction func enter() {
    userIsInTheMiddleOfTypingNumber = false
    operandStack.append(displayValue)
    println("operandStack = \(operandStack)")
}

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

}
}

1 个答案:

答案 0 :(得分:3)

我认为你的performOperation函数应该在@IBAction函数之外,如下所示:

 @IBAction func operate(sender: UIButton) {
      let operation = sender.currentTitle!
      if userIsInTheMiddleOfTypingNumber {
      enter()
      }
      switch operation {

            case"×": performOperation() { $0 * $1 }  - THIS IS THE CODE WHERE WE GOT ERROR
      //            case"÷":
      //            case"+":
        //            case"-":
            default: break

            }


       }

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