问题
I'm upgrading my code to Swift 2 using error handling with try-catch. I've stuck with closure (NSURLSession), I can't throw inside it.
Generally I'm using such code:
let request = NSURLRequest()
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
throw(ErrorType) // here some errortype enum
}
}
But I'm receiving the error: "Cannot invoke dataTaskWithRequest with an argument list of type …". How can I throw from closure?
回答1:
You can't throw inside a closure because the closure can be called later, when the function is already executed.
In your example the closure is called asynchronously after the URLRequest got a response, at this time the calling function is already executed.
来源:https://stackoverflow.com/questions/32668291/swift-2-throw-from-closure