是否有可能在Swift中捕获异常?给出以下代码:
NSException.raise(NSRangeException,
format: "Now you've gone too far!",
arguments: CVaListPointer(fromUnsafePointer: UnsafePointer()))
Run Code Online (Sandbox Code Playgroud)
是否可以防止异常崩溃整个程序?也就是说,Objective-C中Swift等效的是以下内容:
@try {
[NSException raise:NSRangeException format:@"Now you've gone too far!"];
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试这个计算器代码.如何处理无效的用户输入?
//答案:将标题桥接到Objective-C // https://github.com/kongtomorrow/TryCatchFinally-Swift
这是同样的问题,但在objc但我想在swift中这样做.从NSExpression捕获NSInvalidArgumentException
我想要显示的只是一条消息,如果它不起作用,但现在当用户没有输入正确的格式时我得到一个例外.
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")
}
Run Code Online (Sandbox Code Playgroud)