Advertisement
QwertyAvatar

Untitled

May 25th, 2023
380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.29 KB | None | 0 0
  1. import UIKit
  2.  
  3. class ViewController: UIViewController {
  4.  
  5.     @IBOutlet weak var number1TextField: UITextField!
  6.     @IBOutlet weak var number2TextField: UITextField!
  7.     @IBOutlet weak var resultLabel: UILabel!
  8.    
  9.     override func viewDidLoad() {
  10.         super.viewDidLoad()
  11.     }
  12.  
  13.     @IBAction func calculateButtonTapped(_ sender: UIButton) {
  14.         guard let number1Text = number1TextField.text, let number2Text = number2TextField.text else {
  15.             return
  16.         }
  17.        
  18.         guard let number1 = Int(number1Text), let number2 = Int(number2Text) else {
  19.             resultLabel.text = "Invalid input"
  20.             return
  21.         }
  22.        
  23.         var result: Int?
  24.         switch sender.tag {
  25.         case 0: // Addition
  26.             result = number1 + number2
  27.         case 1: // Subtraction
  28.             result = number1 - number2
  29.         case 2: // Multiplication
  30.             result = number1 * number2
  31.         case 3: // Division
  32.             if number2 != 0 {
  33.                 result = number1 / number2
  34.             } else {
  35.                 resultLabel.text = "Cannot divide by zero"
  36.             }
  37.         default:
  38.             break
  39.         }
  40.        
  41.         if let resultValue = result {
  42.             resultLabel.text = String(resultValue)
  43.         }
  44.     }
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement