将Swift字符串公式转换为实数计算 [英] Swift string formula into a real calculation
本文介绍了将Swift字符串公式转换为实数计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有几个公式存储在Plist中,例如A * B.我试图找出如何将此公式当前存储为Plist中的字符串并将其用作实际计算公式。我尝试将制定公式的路线设置为\(A)* \(B),然后在尝试使用公式之前设置A和B,但它不起作用。有什么建议吗?
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?
示例
let A = 5
let B = 2
println (formula)
实际打印出来 \(A)* \(B)
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)
}
这篇关于将Swift字符串公式转换为实数计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文