XCode How to evaluate String formula with an X expression inside

前端 未结 3 746
星月不相逢
星月不相逢 2020-12-18 14:40

I\'m tring to evaluate a string formula to a float but, I cannot find a solution. Here is an example. I need to calculate about 200 formulas in this way.

-          


        
3条回答
  •  攒了一身酷
    2020-12-18 15:27

    Swifty Answer,

    let formula = "12.845*x+(-0.505940)"
    let x = 12
    
    let expr = NSExpression(format: formula)
    let object = ["x":x]
    
    let result = expr.expressionValue(with: object, context: nil)
    
    print(result)
    //Output: 153.63406
    

提交回复
热议问题