由于Swift目前没有try-catch,我怎么能防止这行代码中出现错误数据崩溃?
var myObject = NSKeyedUnarchiver.unarchiveObjectWithData(data) as MyClass
更新
我在操场上创建了一个非常简单的案例进行演示。假设我们不知道data
中的内容,我怎样才能在第二行捕获SIGABRT?在调用unarchiveObjectWithData
之前,是否无法检查以确保可以取消归档NSData对象?
var data = "foo bar".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
if let unarc = NSKeyedUnarchiver.unarchiveObjectWithData(data) { // Execution was interrupted: signal SIGABRT
}
答案 0 :(得分:6)
我认为现在最好的选择是,在Apple更新NSKeyedUnarchiver的实现以不使用异常或向Swift添加异常支持之前,您将不得不使用Objective-C包装器来尝试捕获。
您可以在此处查看包装器的示例: https://medium.com/swift-programming/adding-try-catch-to-swift-71ab27bcb5b8
基本上,您可以引入一个Objective-C函数或类,它允许您使用Swift中的try-catch块。我喜欢将上面的例子作为初始化程序实现,以使其在Swift中更清晰:
// In Objective-C
// ----------------------
@interface try: NSObject
- (id)initWithTry:(void(^)())try catch:(void(^)(NSException *exception))catch finally:(void(^)())finally;
@end
@implementation try
- (id)initWithTry:(void(^)())try catch:(void(^)(NSException *exception))catch finally:(void(^)())finally
{
self = [super init];
if (self) {
@try {
try ? try() : nil;
}
@catch (NSException *exception) {
catch ? catch(exception) : nil;
}
@finally {
finally ? finally() : nil;
}
}
return self;
}
@end
// From Swift (make sure you import the objc header in your bridging header
// ----------------------
var data = "foo bar".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
try(
try: { () -> Void in
if let unarc: AnyObject = NSKeyedUnarchiver.unarchiveObjectWithData(data) { // Execution was interrupted: signal SIGABRT
println(unarc)
}
},
catch: { exception in
println("Failed to parse data: \(exception)")
},
finally: nil
)