Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift string formula into a real calculation

Tags:

ios

swift

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)"

like image 589
ddpishere Avatar asked Mar 17 '15 01:03

ddpishere


3 Answers

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)
}
like image 167
Leo Dabus Avatar answered Nov 18 '22 03:11

Leo Dabus


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.

like image 44
Léo Natan Avatar answered Nov 18 '22 04:11

Léo Natan


@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
like image 2
J.S. Avatar answered Nov 18 '22 04:11

J.S.