Swift 2.0操作员

Swift 2.0操作员,swift,Swift,为什么我可以这样做: number *= operand number += operand 但不是这样(没有得到正确的结果): 8-3给我-5,8/2给我0。如果我这样做 number = operand / displayValue number = operand - displayValue 我得到了正确的答案 一般来说,我对swift和iOS开发还不熟悉。谢谢你的回答 这是简单计算器中的实际代码: class ViewController: UIViewController {

为什么我可以这样做:

number *= operand
number += operand
但不是这样(没有得到正确的结果):

8-3给我-5,8/2给我0。如果我这样做

number = operand / displayValue
number = operand - displayValue
我得到了正确的答案

一般来说,我对swift和iOS开发还不熟悉。谢谢你的回答

这是简单计算器中的实际代码:

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    var isFirstDigit = true
    var operand1: Double = 0
    var operation = "="

    var displayValue: Double {

        get {
            return NSNumberFormatter().numberFromString(label.text!)!.doubleValue
        }

        set {
            label.text = String(format: "%.0f ", newValue)
            isFirstDigit = true
            operation = "="
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


    @IBAction func digit(sender: UIButton) {
        let digit = sender.currentTitle!
        label.text = isFirstDigit ? digit : label.text! + digit
        isFirstDigit = false
    }

    @IBAction func cancel(sender: AnyObject) {
         displayValue = 0
    }

    @IBAction func calculate(sender: UIButton) {
        switch operation {
            case "/": displayValue /= operand1
            case "*": displayValue *= operand1
            case "+": displayValue += operand1
            case "-": displayValue -= operand1
            default: break
        }
    }

    @IBAction func operations(sender: UIButton) {
        operation = sender.currentTitle!
        operand1  = displayValue
        isFirstDigit = true
    }
}

我在操场上试过这个,看起来效果不错

编辑:

我已在XCode上检查了您的代码,并通过更改以下内容解决了此问题:

// Runs the operations.
switch operation {

    case "/": operand1 /= displayValue
    case "*": operand1 *= displayValue
    case "+": operand1 += displayValue
    case "-": operand1 -= displayValue

    default: break
    }

    // Updates the text on the Label.
    label.text = "\(operand1)"

似乎是以相反的顺序执行操作,这解释了为什么“+”和“*”工作正常,但“/”和“-”却不能正常工作。你得到了什么结果?变量的值是什么?似乎数学中的联想属性不适用于除法和减法,这就是为什么它给了我一个负数,谢谢!没问题,很高兴我能帮忙~你愿意接受这个问题的答案吗?
// Runs the operations.
switch operation {

    case "/": operand1 /= displayValue
    case "*": operand1 *= displayValue
    case "+": operand1 += displayValue
    case "-": operand1 -= displayValue

    default: break
    }

    // Updates the text on the Label.
    label.text = "\(operand1)"