我刚刚升级到 Xcode 6.3 和 Swift 1.2,并且正在更新语法。在我的项目中,我使用 TCBlobDownloadSwift用于一些常规下载任务。更新后,我从框架的以下方法中收到编译器错误“'NSError' is not convertible to 'NSError?'”:
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError sessionError: NSError?) {
let download = self.downloads[task.taskIdentifier]!
var error: NSError? = sessionError ?? download.error
// Handle possible HTTP errors
if let response = task.response as? NSHTTPURLResponse {
// NSURLErrorDomain errors are not supposed to be reported by this delegate
// according to https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/NSURLSessionConcepts/NSURLSessionConcepts.html
// so let's ignore them as they sometimes appear there for now. (But WTF?)
if !validateResponse(response) && (error == nil || error!.domain == NSURLErrorDomain) {
error = NSError(domain: kTCBlobDownloadErrorDomain,
code: TCBlobDownloadError.TCBlobDownloadHTTPError.rawValue,
userInfo: [kTCBlobDownloadErrorDescriptionKey: "Erroneous HTTP status code: \(response.statusCode)",
kTCBlobDownloadErrorFailingURLKey: task.originalRequest.URL,
kTCBlobDownloadErrorHTTPStatusKey: response.statusCode])
}
}
// Remove reference to the download
self.downloads.removeValueForKey(task.taskIdentifier)
dispatch_async(dispatch_get_main_queue()) {
download.delegate?.download(download, didFinishWithError: error, atLocation: download.resultingURL)
return
}
}
}
不知何故,我无法再将 NSError
(使用 initWithDomain:code:userInfo
初始化)分配给 error
(NSError?)。 Swift 1.2 有什么变化?我应该如何解决这个问题?
返回 NSError?
在网络相关函数中似乎很正常,尤其是在使用 objC 库的情况下。我现在对携带错误的最佳方式感到困惑,我应该使用 NSError
、NSError?
还是 NSErrorPointer
?
最佳答案
所以我解决了这个问题,事实证明为 NSError 分配一个可选值并没有错。我传递给 NSError
的 init 方法的 userInfo
字典从 NSURLSessionTask
的 OriginalRequest
中获取一个 URL,它是一个 NSURLRequest
。此属性现在更改为 NSURL?
。我更改为 task.originalRequest.URL!
并且成功了。
我想我会继续使用 NSError?
来传递错误。
关于ios - 'NSError' 不可转换为 'NSError?',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29553930/