表达式内的NSExpression自定义变量

时间:2015-06-15 21:36:01

标签: ios objective-c swift expression

最近我发现了NSExpression类,我想知道是否有可能在表达式中评估自定义变量。

这样的事情:

5+4+MYVAR*5

我想用自定义Double值替换此MYVAR字符串。

如果这不存在,我将使用循环和类似的,但希望有一个内置(和更快)的解决方案。

感谢。

1 个答案:

答案 0 :(得分:4)

let myInt = 4
let myFormulaInt = "5 + 4 + myInt * 5"
let intElements = ["myInt": myInt]

let myResultInt = NSExpression(format: myFormulaInt).expressionValueWithObject(intElements, context: nil).integerValue

println(myResultInt)   // 29


let myDouble = 2.5
let myFormulaDouble = "5 + 4 + myDouble * 5"
let doubleElements = ["myDouble": myDouble]

let myResultDouble = NSExpression(format: myFormulaDouble).expressionValueWithObject(doubleElements, context: nil).doubleValue

println(myResultDouble)   // 21.5

Xcode 8 GM•Swift 3

let myInt = 4
let myFormulaInt = "5 + 4 + myInt * 5"
let intElements: [String:Int] = ["myInt": myInt]

let myResultInt = NSExpression(format: myFormulaInt).expressionValue(with: intElements, context: nil) as! Int

print(myResultInt)   // 29


let myDouble = 2.5
let myFormulaDouble = "5 + 4 + myDouble * 5"
let doubleElements: [String: Double] = ["myDouble": myDouble]

let myResultDouble = NSExpression(format: myFormulaDouble).expressionValue(with: doubleElements, context: nil) as! Double

print(myResultDouble)   // 21.5