一尘不染

斯威夫特字符串公式成真实计算

swift

我在A * B等Plist中存储了多个公式。我试图弄清楚如何将当前以字符串形式存储在Plist中的此公式用作实际计算公式。我尝试过将公式制作为\(A)*
\(B),然后在尝试使用公式之前设置A和B的方法,但这没有用。有什么建议?

let A = 5
let B = 2

println (formula)

实际打印出“ \(A)* \(B)”


阅读 253

收藏
2020-07-07

共1个答案

一尘不染

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)
}
2020-07-07