Search code examples
swiftmathnullformatnsexpression

How to get nil if something can't be evaluated?


I am using NSExpression to solve strings from user input. Here is the code

var userInput = "5+"
var solveUserInput = NSExpression(format: "\(userInput)")

It will crash my program because it can't solve it, but what I want to do is to return nil if the string is unsolvable by NSExpression. Is there any way to do this?


Solution

  • NSExpression is not really meant for that kind of usage (evaluation of user input).

    I suggest that you have a look at DDMathParser instead.