I am trying this code that is a calculator. How can I handle input from the user that is not valid?
//ANSWER: Bridging header to Objective-C// https://github.com/kongtomorrow/TryCatchFinally-Swift
Here is the same question but in objc but I want to do this in swift. Catching NSInvalidArgumentException from NSExpression
All I want to show is a message if it doesn't work, but now I am getting an exception when the user doesn't input the correct format.
import Foundation
var equation:NSString = "60****2" // This gives a NSInvalidArgumentException',
let expr = NSExpression(format: equation) // reason: 'Unable to parse the format string
if let result = expr.expressionValueWithObject(nil, context: nil) as? NSNumber {
let x = result.doubleValue
println(x)
} else {
println("failed")
}
A nice solution editing from https://github.com/kongtomorrow/TryCatchFinally-Swift:
First create
TryCatch.h
&TryCatch.m
and bridge them to Swift:TryCatch.h
TryCatch.m
Then create the class
TryCatch
in Swift:Finally, use it! :)
More "Swifty" solution:
This will generate Swift code:
And you can use it with
try
:This is still an issue in Swift 2. As noted, the best solution is to use a bridging header and catch the NSException in Objective C.
https://medium.com/swift-programming/adding-try-catch-to-swift-71ab27bcb5b8 describes a good solution, but the exact code doesn't compile in Swift 2 because
try
andcatch
are now reserved keywords. You'll need to change the method signature to workaround this. Here's an example: