NSExpression custom variables inside expression

后端 未结 1 1890
生来不讨喜
生来不讨喜 2020-12-19 19:28

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

Something like this:

1条回答
  •  有刺的猬
    2020-12-19 19:43

    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
    

    0 讨论(0)
提交回复
热议问题