NSExpression error handling

Context: SwiftUI TextField with a String for simple math using NSExpression.

I first prepare the input string to an extent but a malformed input using valid characters still fails, as expected. Let's say preparedExpression is "5--"

let expr = NSExpression(format: preparedExpression)
 

gives

FAULT: NSInvalidArgumentException: Unable to parse the format string "5-- == 1"; (user info absent)

How can I use NSExpression such that either the preparedExpression is pre-tested before asking for actual execution or the error is handled in a polite way that I can use to alert the user to try again.

Is there a Swift alternative to NSExpression that I've missed?

Answered by DTS Engineer in 820388022

This error is an Objective-C language exception. For an explanation as to what that means, see What is an exception?

You can’t catch such exceptions in Swift. If you absolutely have to do that, your only option is to write an Objective-C wrapper that catches the exception and then returns it within an NSError. Oh, and that wrapper can’t use ARC, it has to be MRR (manual retain/release).

Having said that, the NSExpression parser wasn’t really designed to accept arbitrary user input. Using it that way can result in problems. For example:

  • If the expression uses a placeholder (%@) and you don’t supply one.

  • An expression can access arbitrary object properties via key paths.

If you want to turn user input into an expression, I recommend that you write or acquire your own parser.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

This error is an Objective-C language exception. For an explanation as to what that means, see What is an exception?

You can’t catch such exceptions in Swift. If you absolutely have to do that, your only option is to write an Objective-C wrapper that catches the exception and then returns it within an NSError. Oh, and that wrapper can’t use ARC, it has to be MRR (manual retain/release).

Having said that, the NSExpression parser wasn’t really designed to accept arbitrary user input. Using it that way can result in problems. For example:

  • If the expression uses a placeholder (%@) and you don’t supply one.

  • An expression can access arbitrary object properties via key paths.

If you want to turn user input into an expression, I recommend that you write or acquire your own parser.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

NSExpression error handling
 
 
Q