Advertisement
ZTCYING

Lab2- calculator

May 4th, 2024 (edited)
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.05 KB | None | 0 0
  1. //
  2. //  ViewController.swift
  3. //  Calculator
  4. //
  5. //  Created by Sabin Tabirca on 29/01/2024.
  6. //
  7.  
  8. import UIKit
  9.  
  10. class ViewController: UIViewController {
  11.    
  12.     // outlet and actions
  13.    
  14.     @IBOutlet weak var screen: UITextField!
  15.    
  16.     @IBAction func clearAction(_ sender: Any) {
  17.         // clear screen and reset vars
  18.         screen.text = ""
  19.          
  20.     }
  21.    
  22.     @IBAction func equalAction(_ sender: Any) {
  23.         // get the current value
  24.         let currentValue = screen.text!
  25.        
  26.         // convert them
  27.         let value1 = Double(screenValue)!
  28.         let value2 = Double(currentValue)!
  29.         var result : Double = 0
  30.        
  31.         switch oper{
  32.         case "+":
  33.             result = value1 + value2
  34.             screen.text = String(result)
  35.            
  36.         case "-":
  37.             result = value1 - value2
  38.             screen.text = String(result)
  39.            
  40.         case "*":
  41.             result = value1 * value2
  42.             screen.text = String(result)
  43.         case "/":
  44.             if value2 != 0{
  45.                 result = value1 / value2
  46.                 screen.text = String(result)}
  47.             else{
  48.                 screen.text = "ERROR"
  49.             }
  50.            
  51.         default:break
  52.         }
  53.        
  54.        
  55.     }
  56.    
  57.     @IBAction func operationAction(_ sender: Any) {
  58.         // memorise the operation to compute
  59.         oper = ((sender as! UIButton).titleLabel?.text)!
  60.        
  61.         // memorise teh screen value
  62.         screenValue = screen.text!
  63.        
  64.         // clear the screen
  65.         screen.text = ""
  66.     }
  67.    
  68.     @IBAction func digitAction(_ sender: Any) {
  69.         // append the button label to screen's text
  70.         let screenText = screen.text
  71.         let digit = (sender as! UIButton).titleLabel?.text
  72.         screen.text = "\(screenText!)\(digit!)"
  73.     }
  74.    
  75.    
  76.     // vars
  77.     var oper = ""
  78.     var screenValue = ""
  79.  
  80.     override func viewDidLoad() {
  81.         super.viewDidLoad()
  82.         // Do any additional setup after loading the view.
  83.     }
  84.  
  85.  
  86. }
  87.  
  88.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement