相关疑难解决方法(0)

在Swift中尝试捕获异常

是否有可能在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)

exception try-catch swift

28
推荐指数
1
解决办法
4万
查看次数

在swift中捕获无效用户输入的异常

我正在尝试这个计算器代码.如何处理无效的用户输入?

//答案:将标题桥接到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)

cocoa-touch exception-handling ios nsexpression swift

11
推荐指数
2
解决办法
3039
查看次数