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
576 views
in Technique[技术] by (71.8m points)

ios - NSExpression custom variables inside expression

Recently I have discovered NSExpression class and I am wondering is there a possibility to evaluate custom variables inside expression.

Something like this:

5+4+MYVAR*5

I would like to replace this MYVAR string with custom Double value.

If this don't exists, I will go with loops and similar, but hoping that there is a built-in (and faster) solution.

Thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
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

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

...