【发布时间】:2019-05-02 13:15:10
【问题描述】:
我在尝试创建自己的通用闭包时遇到此错误。
我找不到这个问题的任何潜在解决方案。
完整代码:
func customRequest<T : Codable>(_ target: Api, whenSuccess: @escaping CustomCompletion<T>, whenError: @escaping (String) -> Void) {
super.request(target, callbackQueue: .none, progress: .none, completion: { result in
switch result {
case let .success(response):
if let data = try? JSONDecoder().decode(BaseAPIModel<T>.self, from: response.data) {
if data.isValid(), let result = data.result {
whenSuccess(result)
} else {
whenError(data.toErrorReadableString())
}
} else {
whenError("Something had gone wrong. Please try again.")
}
case let .failure(error):
if let response = error.response, let data = try? JSONDecoder().decode(BasicAPIModel.self, from: response.data) {
whenError(data.toErrorReadableString())
} else {
whenError("Something had gone wrong. Please try again.")
}
}
})
}
fileprivate func getLogo() {
// Error come from this line
ApiProvider().customRequest(Api.prefetchLogo, whenSuccess: { _ in
}, whenError: { (error) in
})
}
【问题讨论】:
-
这取决于
Api和CustomCompletion是什么。我建议您在所有内容上都提供明确的类型,直到错误更清楚为止。例如,与其为whenSuccess传递闭包,不如显式创建一个CustomCompletion变量并传递它(whenError相同)。通过将事物分配给明确类型的变量,编译器可以更轻松地告诉您哪里出错了。 -
Api是一个枚举,CustomCompletion指的是public typealias CustomCompletion<T> = (_ result: T) -> Void