如何解决“无法推断通用参数‘T’"?在斯威夫特 [英] How can I solve "Generic parameter 'T' could not be inferred" in Swift

查看:30
本文介绍了如何解决“无法推断通用参数‘T’"?在斯威夫特的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构和函数.

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.

这篇关于如何解决“无法推断通用参数‘T’"?在斯威夫特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆