使用通用闭包时,表达式类型'()'不明确,没有更多上下文

时间:2019-05-02 13:15:10

标签: swift generics

尝试创建自己的通用闭包时出现此错误。

我找不到解决此问题的任何可能的方法。

完整代码:

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

        })
    }

1 个答案:

答案 0 :(得分:0)

编译器无法确定T的代码类型为CustomCompletion<T>。提供它的方式有两种。

将其添加到customRequest的传递参数中,例如作为fetching参数:

func customRequest<T : Codable>(_ target: Api, fetching: T.Type, 
                                whenSuccess: @escaping CustomCompletion<T>, 
                                whenError: @escaping (String) -> Void) {

那么它将被称为:

ApiProvider().customRequest(Api.prefetchLogo, fetching: Something.self, ...

或在闭包参数中添加类型:

ApiProvider().customRequest(Api.prefetchLogo, whenSuccess: { (_: Something) in

尽管您不在乎返回的值是什么,但是编译器仍然必须生成代码以对其进行解码,并且它需要以某种方式知道其类型。