Swift 2.0 运算符

标签 swift

为什么我能做到这一点:

number *= operand
number += operand

但不是这个(没有得到正确的结果):

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
    }
}

最佳答案

我已经在 Playground 上尝试过了,看起来效果很好。

enter image description here

编辑:

我已经在 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)"

看起来您正在以相反的顺序执行操作,这解释了为什么“+”和“*”可以正常工作,但“/”和“-”却不能正常工作。

关于Swift 2.0 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34193317/

相关文章:

swift - 如何检测 amp 页面的 url 何时使用 WKWebview 更改

swift - 将文档数据传递给优胜美地中的 View Controller ( Storyboard)

ios - UIDocumentPickerViewController 委托(delegate)在演示者的 viewWill/DidAppear 之前调用

Swift/OSX - 如何在不运行应用程序的情况下授予单元测试核心数据访问权限并运行测试

ios - 如何使用手动UITabbar并使用它来切换其他ViewController?

javascript - ReactNative native-modules Promise 传递字段和 Swift

xcode - Swift 函数卡住

ios - 如何在表格 View 中正确设置动态标题 View ?

swift - NSCollectionView 如何在没有 item 的情况下绘制文本?

ios - Swift:什么是 .swift-version 文件?