'Evaluate String expression in Swift just like javascript eval

I am getting dynamic conditions through API to apply in the application. It could be any logical expression. The task is to run all the condition received in mobile app and proceed further as per the result of evaluation.

Example :

"conditionInfos": [
    {
      "errorMessage": "Error message",
      "condition": "@City == \"xyz\" AND @Hobby == "\"gardening\""
    },
    {
      "errorMessage": "error",
      "condition": "@CountryCode == +91 OR @CountryCode == +1",
    }

I am replacing value of entities (prefixed with @) with the actual values & the logical separator if any like AND and OR with respective (&&, ||) symbols.

The string expression then created needs to be evaluate.

I checked NSExpression in swift but that works only for Mathematical expressions and is throwing error in my case.

I saw same had been done through eval in javascript and I need same for Swift language.

Kindly guide.



Solution 1:[1]

JavaScriptCore Framework bundled with Xcode seems helpful to evaluate JS code. The below code runs in the playground.

import JavaScriptCore
let context:JSContext = JSContext()

context.evaluateScript("var factorial = function(n) { if(n<0){return;}if(n===0){return 1;}return n*factorial(n-1); }")

let result: JSValue = context.evaluateScript("factorial(3)")

print(result.toInt32()) // => 6

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tana005