Swift 2:从闭包中抛出 [英] Swift 2: Throw from closure
问题描述
我正在使用带有 try-catch 的错误处理将我的代码升级到 Swift 2.我一直在使用闭包 (NSURLSession),我不能把它扔进去.
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
}
}
但我收到错误消息:无法使用类型为……的参数列表调用 dataTaskWithRequest".我怎样才能从闭包中抛出?
But I'm receiving the error: "Cannot invoke dataTaskWithRequest with an argument list of type …". How can I throw from closure?
推荐答案
你不能在闭包内部抛出,因为闭包可以在稍后调用,当函数已经执行时.
You can't throw inside a closure because the closure can be called later, when the function is already executed.
在您的示例中,在 URLRequest 得到响应后异步调用闭包,此时调用函数已经执行.
In your example the closure is called asynchronously after the URLRequest got a response, at this time the calling function is already executed.
这篇关于Swift 2:从闭包中抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!