Swift 2:从闭包中抛出

Swift 2: Throw from closure

我正在将我的代码升级到 Swift 2,使用带有 try-catch 的错误处理。我坚持使用闭包(NSURLSession),我不能把它扔进去。

一般我都在用这样的代码:

let request = NSURLRequest()

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in
    if error != nil {
        throw(ErrorType) // here some errortype enum
    }
}

但我收到错误消息:"Cannot invoke dataTaskWithRequest with an argument list of type …"。我怎样才能从闭包中抛出?

您不能在闭包中抛出异常,因为闭包可以稍后调用,当函数已经执行时。

在你的例子中闭包是在 URLRequest 得到响应后异步调用的,此时调用函数已经执行。