Apple在Swift 2中引入了新的错误处理
我正在使用AFNetoworking v2.x的项目,其中AFHTTPRequestSerializer有2个选择器:
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters DEPRECATED_ATTRIBUTE;
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
error:(NSError * __autoreleasing *)error;
首先弃用,但第二个由Swift 2编译器自动转换为第一个签名。现在不允许使用老式方法:
var error: NSError?
let request = self!.operationManager.requestSerializer.requestWithMethod(method, URLString: url?.absoluteString, parameters: params, error: error)
给了我一个编译时错误:
Cannot convert value of type 'NSError?' to expected argument type '()'
但是全新的表示法会将选择器与错误处理减少到没有它的弃用变体。
do {
let request = try
self!.operationManager.requestSerializer.requestWithMethod(method, URLString: url?.absoluteString, parameters: params)
} catch let error as NSError {
// ...
}
Swift 2中解决此问题的最佳做法是什么?在这种情况下有没有办法指定某个选择器?
UPD:Swift 2功能的更精确链接成为我问题的原因。 https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-ID10
答案 0 :(得分:0)
似乎这在Xcode 7.1中正常工作(我记得在7.0中有这个问题)只是改变你的方法使用错误指针,即&error
var error: NSError?
let request = self!.operationManager.requestSerializer.requestWithMethod(method, URLString: url?.absoluteString, parameters: params, error: &error)
答案 1 :(得分:-1)
Swift 2更喜欢仅为必要的方法提供Try Catch块。因此,如果您的方法有可能需要错误处理的情况,那么只提供此块。
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let NSError = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}