Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // ViewController.swift
- // Calculator
- //
- // Created by Milos on 4/3/18.
- // Copyright © 2018 Milos. All rights reserved.
- //
- import UIKit
- enum Operation:String {
- case ADDITION = "+"
- case SUBSTRACTION = "-"
- case DIVISION = "/"
- case MULTIPLICATION = "*"
- case NULL = "Null"
- }
- class ViewController: UIViewController {
- @IBOutlet weak var outputLbl: UILabel!
- var val1 = ""
- var val2 = ""
- var runningNumber = ""
- var runningOpNum = ""
- var res = ""
- var currentOperation:Operation = .NULL
- override func viewDidLoad() {
- super.viewDidLoad()
- outputLbl.text = "0"
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- }
- @IBAction func numberPressed(_ sender: RoundButton) {
- if runningNumber.count <= 8 {
- runningNumber += "\(sender.tag)"
- outputLbl.text = runningNumber
- }
- }
- @IBAction func allClearPressed(_ sender: RoundButton) {
- val1 = ""
- val2 = ""
- runningNumber = ""
- res = ""
- currentOperation = .NULL
- outputLbl.text = "0"
- }
- @IBAction func equalPressed(_ sender: RoundButton) {
- operation(operation: currentOperation)
- val1 = ""
- val2 = ""
- runningNumber = ""
- res = ""
- currentOperation = .NULL
- }
- @IBAction func addPressed(_ sender: RoundButton) {
- operation(operation: .ADDITION)
- if outputLbl.text != "0"{
- outputLbl.text = "+"
- }
- }
- @IBAction func substractPressed(_ sender: RoundButton) {
- operation(operation: .SUBSTRACTION)
- if outputLbl.text != "0"{
- outputLbl.text = "-"
- }
- }
- @IBAction func multiplyPressed(_ sender: RoundButton) {
- operation(operation: .MULTIPLICATION)
- if outputLbl.text != "0"{
- outputLbl.text = "*"
- }
- }
- @IBAction func dividePressed(_ sender: RoundButton) {
- operation(operation: .DIVISION)
- if outputLbl.text != "0"{
- outputLbl.text = "/"
- }
- }
- func operation(operation: Operation) {
- if currentOperation != .NULL {
- if runningNumber != "" {
- val2 = runningNumber
- runningNumber = ""
- switch currentOperation {
- case .ADDITION:
- res = "\(Double(val1)! + Double(val2)!)"
- case .SUBSTRACTION:
- res = "\(Double(val1)! - Double(val2)!)"
- case .MULTIPLICATION:
- res = "\(Double(val1)! * Double(val2)!)"
- case .DIVISION:
- res = "\(Double(val1)! / Double(val2)!)"
- case .NULL: break
- }
- if (Double(res)!.truncatingRemainder(dividingBy: 1) == 0) {
- res = "\(Int(Double(res)!))"
- }
- outputLbl.text = val1 + currentOperation.rawValue + val2 + "=" + res
- }
- currentOperation = operation
- }else {
- val1 = runningNumber
- runningNumber = ""
- currentOperation = operation
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement