I have several formulas stored in a Plist such as A * B. I'm trying to figure out how I could take this formula currently stored as a string in a Plist and use it as an actual calculation formula. I tried going the route of making the formula to \(A) * \(B) and then setting A and B before trying to use the formula but it did not work. Any suggestions?
example
let A = 5
let B = 2
println (formula)
actually printed out "\(A) * \(B)"
Xcode 8.3.1 • Swift 3.1
extension String {
var expression: NSExpression {
return NSExpression(format: self)
}
}
let a = 5
let b = 2
let intDictionary = ["a": a,"b": b]
var formula = "a * b"
if let timesResult = formula.expression.expressionValue(with: intDictionary, context: nil) as? Int {
print(timesResult) // 10
}
formula = "(a + b) / 2"
if let intAvgResult = formula.expression.expressionValue(with: intDictionary, context: nil) as? Int {
print(intAvgResult) // 3
}
let x = 5.0
let y = 2.0
let z = 3.0
let doubleDictionary = ["x": x, "y": y, "z": z]
formula = "(x + y + z) / 3"
if let doubleAvgResult = formula.expression.expressionValue(with: doubleDictionary, context: nil) as? Double {
print(doubleAvgResult)
}
Use NSExpression
.
NSExpression *expression = [NSExpression expressionWithFormat:@"4 + 5 - 2**3"];
id value = [expression expressionValueWithObject:nil context:nil]; // => 1
Expression creation is formatted, so you can input your params as part of the equation.
More info here.
@Leo for Swift 3 (as opposed to obj-c) in Xcode 8 it would look like this:
let mathExpression = NSExpression(format: "4 + 5 - 2**3")
let mathValue = mathExpression.expressionValue(with: nil, context: nil) as? Int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With