Swift 2: Throw from closure

╄→гoц情女王★ 提交于 2019-12-12 03:38:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!