Skip to content

Instantly share code, notes, and snippets.

@vukcevich
Created August 22, 2017 22:00
Show Gist options
  • Select an option

  • Save vukcevich/56410e5044a58e77384ec5c5a84eece4 to your computer and use it in GitHub Desktop.

Select an option

Save vukcevich/56410e5044a58e77384ec5c5a84eece4 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import Foundation
import UIKit
//As reference:
//https://spin.atomicobject.com/2015/03/24/evaluate-string-expressions-ios-objective-c-swift/
/**
NSExpression
*/
let b = "3+3"
let c = "2+5+10*2+2/2*2/1+2+4"
//let c1 = 2+5+10*2+2/2*2/1+2+4
let exp = NSExpression(format: c)
let v = exp.expressionValue(with: nil, context: nil) as! NSNumber
print(#line, "dbg-v]:", v)
var logicalExpression = "1 + 2 > 2 || 4 - 2 = 0"
let predicate = NSPredicate(format: logicalExpression)
var result = predicate.evaluate(with:"") as Bool
print(#line, "dbg-result]:", result)
var numericExpression = "sqrt(4 + 2 - 2)" // + log(5)"
let expression = NSExpression(format: numericExpression)
var resultN = expression.expressionValue(with:nil, context: nil) as! NSNumber
print(#line, "dbg-resultN]:", resultN)
public extension NSNumber {
func squareAndSubtractFive() -> NSNumber {
return NSNumber(value: (self.doubleValue * self.doubleValue) - 5 )
}
}
var stringExpression = "function(5, 'squareAndSubtractFive')"
let expressionE = NSExpression(format: stringExpression)
var resultE = expressionE.expressionValue(with:nil, context: nil) as! NSNumber
print(#line, "dbg-resultE]:", resultE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment