Reputation: 33
Just gonna warn you, I'm brand new to swift and I'm still getting used to how this works. I've been trying to work on this Calculator project for class. The problem is, I need practice simplifying code.
Right now, when a number button is pressed, I have it saved in an array like this.
@IBAction func buttonPressed(_ sender: UIButton) {
if numBtnPressed == true {
numArray.append(sender.title(for: .normal)!)
}
}
so if the button labeled 1 is pressed, it stores ["1"] as a string in the empty array numArray
I have a separate structure for operators in case I need it.
struct calcFuncs {
var add : String
var subtract : String
var divide : String
var multiply : String
}
var calc = calcFuncs(add: "+", subtract: "-", divide: "/", multiply: "x")
I'm trying to figure out how to have a string of numbers and operators (example 1 + 2 x 3 + 4 / 5 + 5) and have the compiler save that calculation, then print it when equal is pressed. I know I have to find a way to have calculations done even though everything is in a string right now. I want it to print the finished string on a label.
I'm stuck on how to pull the items from the array and have an operator appear inbetween depending on what operator was clicked. ("[1] (operator) [2] (operator) [3] (operator)") and have it print a sum.
I was thinking something like this but I know its tedious and probably won't work:
for 0...1 in index:
[0] something [1]
1...2 in index:
etc etc
I know this sounds insane, but I'm struggling telling the computer what I want (calculate a string of numbers when these buttons are pressed, save the total, then print total when equal is clicked) and putting that into clean-cut code.
Any advice at all, even if it means changing all my code, is appreciated.
Upvotes: 3
Views: 7260
Reputation: 109
Calculator for swift 4
class ViewController: UIViewController {
var numberOnScreen: Double = 0;
var previousNumber: Double = 0;
var performingMath = false;
var operation = 0;
@IBOutlet weak var label1: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func btn_pressed(_ sender: Any) {
if performingMath == true {
label1.text = String((sender as AnyObject).tag-1)
numberOnScreen = Double(label1.text!)!
performingMath = false
}
else {
label1.text = label1.text! + String((sender as AnyObject).tag-1)
numberOnScreen = Double(label1.text!)!
}
}
@IBAction func processbtn(_ sender: Any) {
if label1.text != "" && (sender as AnyObject).tag != 11 && (sender as AnyObject).tag != 16{
// 11= AC (clear) , 16 = equalto(=)
// Use tag numbers correctly
previousNumber = Double(label1.text!)!
if (sender as AnyObject).tag == 12 { //Divide
label1.text = "/";
}
if (sender as AnyObject).tag == 13 { //Multiply
label1.text = "x";
}
if (sender as AnyObject).tag == 14 { //Subtract
label1.text = "-";
}
if (sender as AnyObject).tag == 15 { //Add
label1.text = "+";
}
operation = (sender as AnyObject).tag
performingMath = true;
}
else if (sender as AnyObject).tag == 16 {
if operation == 12{ //Divide
label1.text = String(previousNumber / numberOnScreen)
}
else if operation == 13{ //Multiply
label1.text = String(previousNumber * numberOnScreen)
}
else if operation == 14{ //Subtract
label1.text = String(previousNumber - numberOnScreen)
}
else if operation == 15{ //Add
label1.text = String(previousNumber + numberOnScreen)
}
}
else if (sender as AnyObject).tag == 11{
label1.text = ""
previousNumber = 0;
numberOnScreen = 0;
operation = 0;
}
}
}
Upvotes: 0
Reputation: 4411
You have some good ideas, but perhaps there is an easier way. This example uses the tag property of buttons that you can set in Interface Builder, and the NSExpression
class to evaluate the maths. There are many other ways to do it.
This will follow the standard order of operations (multiplication and division before addition and subtraction, for example).
import UIKit
var calculationString = "" // Declare this outside method in view controller
@IBAction func buttonPressed(_ sender: UIButton) {
// Use the tag property of buttons which can be set in Interface Builder
// Number buttons can have tag values 0-9
// Operator buttons can have higher tag numbers (10: "+", 11: "-", 12: "*" 13: "/")
// Decimal point button tag (14)
// Calculate or equals button tag (15)
// Check for tag number
switch sender.tag {
case 0...9:
// Numbers
calculationString.append(String(sender.tag))
case 10:
// Add
calculationString.append("+")
case 11:
// Subtract
calculationString.append("-")
case 12:
// Multiply
calculationString.append("*") // Need to use asterisk for multiply
case 13:
// Divide
calculationString.append("/")
case 14:
// Decimal
calculationString.append(".")
case 15:
// Perform calculation
let expression = NSExpression(format: calculationString)
let result = expression.expressionValue(with: nil, context: nil) ?? 0
yourLabel.text = "Result: \(result)" // Or do whatever you need with the result.
default:
fatalError("Unknown button tag")
}
yourLabel.text = calculationString // Display user input if desired
}
Upvotes: 1