Search code examples
swiftxcodedivisiondivide-by-zero

How divide result from text field to label and get it on another label


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!

Solution

  • 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 to

    @IBAction func equal(_ sender: Any) {
        guard let text = Adam.text, let adamValue = Int(text), adamValue != 0,
              let totalAmountValue = Int(totalAmount.text!) else { return }
    
        let result = totalAmountValue / adamValue
        finish.text = String(result)
    }
    

    By 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

    @IBAction func equal(_ sender: Any) {
        guard let text = Adam.text, let adamValue = Double(text), adamValue != 0,
              let totalAmountValue = Double(totalAmount.text!) else { return }
    
        let result = totalAmountValue / adamValue
        finish.text = String(format: "%.2f", result)
    }