I need to finish(Label) = totalAmount(TextField) / adam (Label).
Here is my code:
import UIKit
var plusAndMinus = 0
class ViewController234: UIViewController {
@IBOutlet weak var adam: UILabel!
@IBAction func plus(_ sender: Any) {
plusAndMinus += 1
adam.text = "(plusAndMinus)"
}
@IBAction func minus(_ sender: Any) {
if(plusAndMinus != 0 ) {
plusAndMinus -= 1
}
adam.text = "(plusAndMinus)"
}
// Write total amonunt to calculate
@IBOutlet weak var totalAmount: UITextField!
@IBAction func equal(_ sender: Any) {
var adam = 0
var totalAmount = 0
var result = 0
adam = Int(adam)
totalAmount = Int(totalAmount)
guard result != 0 else {return}
result = totalAmount / adam
finish.text = String(result)
}
//Show calculated
// finish = totalAmount / adam
@IBOutlet weak var finish: UILabel!
2
Answers
It looks to me like you are only accessing your local variables and not the text fields in the
equal()
function.It is better to use different names for local variables and class properties to avoid confusion.
So first lets validate that the text fields contains values that can be converted to Int variables and otherwise return directly by using
guard
. Then it’s simply a matter of dividing the values but of course we also want to avoid decision by zero so we check that toBy using integers we are doing integer division and thus loosing precision, if you want to keep the precision you can switch to Double in the code above and perhaps add some formatting of the result
I’m not sure what your
finish
label is because you don’t have a label for it, but given that you’re meaning to output your answer to it: