I am relatively new to swift. I made a simple text-based calculator in swift using NSExpression. I have a problem, however: this text-based calculator calculates the first expression typed into it perfectly every time (expressions from 2+4 to 9*7-1/3*2+1), but the second time, the outputted result is always just the same result as the first one (it won't calculate again). Here is the basics of my code:
I call it from a view controller and make a result label's text equal to the result found in the swift file far below:
x.savetextfinal = calculatortextfield.text! // Variable x.savetextfinal, created elsewhere in a struct, is assigned to the user's input.
// Now the magic happens in calculatormath.swift (see below)
print("this is the result \(z.nsexpress2)")
equalsresultlabel.text = "Result is (z.nsexpress2)."
Then this block of code, found in a separate swift file, seems to me to occur. It uses NSExpression to convert the expression from a string to an NSExpression, then creates a variable and assigns the result "result" of the NSExpression "mathExpression" to it as a string.
import Foundation
var nsexpress:String = String(x.savetextfinal)
var mathExpression = NSExpression(format: nsexpress)
var result:Float = Float((mathExpression.expressionValueWithObject(nil, context: nil) as? NSNumber)!)
struct calculatoranswer {
var nsexpress2:String = String(result)
}
var z = calculatoranswer()
Any ideas why this calculator will not calculate an expression twice will be much appreciated! Thanks.
All I had to do was put all of my calculating code in a function and call it in my view controller. Everything in my calculating swift file was put in a function, which I put inside a struct, and I called the function. Everything worked as planned, and I had my calculator. Structs and functions, not too hard even for beginners like me.