【发布时间】:2020-10-09 09:43:27
【问题描述】:
我正在做一些网络工作,想根据响应从尾随闭包中抛出。
因此,我发现由于“无效转换”错误而无法执行此操作。
我已将问题简化为一个最小示例 - 不允许陈词滥调:
func innerClosure(a: String, completion: (String)->Void) {
completion(a + ", World")
}
func iCanThrow(name: String, closure: (String,(String)->Void)->(Void) ) throws {
closure(name, {response in
print (response)
if response == "Hello, World" {
throw ClicheError.cliche
}
})
}
try iCanThrow(name: "Hello", closure: innerClosure)
你可以看到我想从尾随闭包中抛出一个ClicheError - 但具体错误是Invalid conversion from throwing function of type '(String) throws -> Void' to non-throwing function type '(String) -> Void'
我尝试过使用 throws 和 rethrows 的各种组合,但我根本无法让它工作 - 即使我得到 throw 的内部封闭,我得到以下信息:
enum ClicheError: Error {
case cliche
case latecliche
}
func innerClosure(a: String, completion: (String) throws ->Void) {
try? completion(a + ", World")
}
func iCanThrow(name: String, closure: (String,(String) throws ->Void) throws ->(Void) ) throws {
try closure(name, {response in
print (response)
if response == "Hello, World" {
throw ClicheError.cliche
}
})
}
try iCanThrow(name: "Hello", closure: innerClosure)
从iCanThrow 编译、抛出但实际上并没有抛出——这意味着我不能抛出!
【问题讨论】:
-
对于网络请求,您也可以使用
Result类型,例如stackoverflow.com/a/54597264/1187415。
标签: swift