Reputation: 708
Why I can do this:
number *= operand
number += operand
but not this (not getting the right result):
number /= operand
number -= operand
8 - 3 gives me -5 and 8 / 2 gives me 0. If I do
number = operand / displayValue
number = operand - displayValue
I get the right answer.
I'm new to swift and iOS development in general. Thanks for your answer!
This is the actual code from the simple calculator:
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
}
}
Upvotes: 2
Views: 83
Reputation: 278
I have tried this on Playground and it seems to be working just fine.
EDIT:
I have checked your code on XCode and was able to fix the issue by changing this:
// 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)"
It seems like you were executing the operations in the inverse order, which explains why "+" and "*" were working properly but not "/" and "-".
Upvotes: 3