1

I'm using this code to return the calculation of a string:

func calcString(txt: String) -> String {
    let expn = NSExpression(format: txt)
    var final: AnyObject = expn.expressionValueWithObject(nil, context: nil)
    return "\(final)"
}

How can I test that the string contains a valid formula?

Floyd Resler
  • 1,786
  • 3
  • 22
  • 41
  • What formula do you want to test ? What is it that you exactly want to do ? – Sandeep Sep 03 '15 at 20:28
  • I want to test if the mathematical formula contained in the string is a valid one. For example, "(3+1))" would be invalid and I need to test for that so the app doesn't crash. – Floyd Resler Sep 03 '15 at 20:33
  • possible duplicate of [NSExpression catch invalid arguments](http://stackoverflow.com/questions/18421307/nsexpression-catch-invalid-arguments) While your question isn't an exact duplicate (it's about swift which rules out try/catch) the gist of the answer is "You can't do it using `NSExpression`." – David Berry Sep 03 '15 at 21:00
  • You can catch exceptions in Swift 2 now. – Code Different Sep 03 '15 at 21:15

0 Answers0