如何解决“无法推断通用参数‘T’"?在斯威夫特

人气:942 发布:2022-10-16 标签: generics swiftui swift swift5.5

问题描述

我有以下结构和函数.

struct ApiResponse<TResponse: Codable>: Codable {
    var isSuccess: Bool
    var mainResponse: TResponse?
}

public struct SomeResponse: Codable {
    var someProperty: String
}

public func postAsync<TRequest: Codable, TResponse: Codable>(route: String, request: TRequest) async throws -> TResponse? {

    let body = try JsonEncoder().encode(request)
    let urlRequest = createUrlRequest(route: route, method: "POST", body: body)

    let (data, _) = try await URLSession.shared.data(for: urlRequest)
    let apiResponse = try JsonDecoder().decode(ApiResponse<TResponse>.self, from: data)
    return response.mainResponse
}

我想像这样调用 postAsync func 但它说 **Generic parameter 'TResponse' could not be inferred** 我怎样才能调用这个方法?我尝试了不同的方法但没有解决.

I want to call postAsync func like that but it says **Generic parameter 'TResponse' could not be inferred** How can I call this method? I tried different ways but not solve.

 - let res = await postAsync(route: "MyController/Get", request: someRequest) as? SomeResponse
 - let res: SomeResponse = await postAsync(route: "MyController/Get", request: someRequest)

推荐答案

你的函数不返回 SomeResponse,它返回 SomeResponse?,所以你这里的意思是:

Your function doesn't return SomeResponse, it returns SomeResponse?, so what you meant here is:

let res = ... as SomeResponse? // Note `as`, not `as?`

let res: SomeResponse? = ...

我同意 EmilioPaleaz 关于如何改进 API 的意见,但我建议添加一个默认值,这样可以两全其美:

I agree with EmilioPaleaz about how to improve the API, though I would recommend adding a default value, which gives the best of both worlds:

... request: TRequest, returning: TResponse.Type = TResponse.self) async throws -> ...

有了这个,当返回类型已知时,你可以省略它.

With this, when the return type is known, you can omit it.

719