Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

ios - Swift string formula into a real calculation

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...