我该如何修复 Protocol can only be used as a generic constraint because it has Self or associated type requirements 错误

How can I fix Protocol can only be used as a generic constraint because it has Self or associated type requirements error

我知道这个问题已经被问过很多次了,但是我很难理解这如何归因于我的场景。

我希望有人能帮我解决这个问题,这样我就可以理解这个问题以及如何解决。

我有协议

protocol HTTPClientProtocol: class {
    associatedtype T: EndpointProtocol
    associatedtype U: Codable

    var task: URLSessionDataTask { get set }
    var session: SessionProtocol { get }
    var request: URLRequest? { get }

    func call(method: HTTPMethod, endpoint: T, urlParams: [String: String], bodyParams: [String: String], queryParams: [String: String]) -> Promise<U>
    .......
}

还有一个class我用

class HTTPClient<T: EndpointProtocol, U: Codable>: HTTPClientProtocol {
    var task: URLSessionDataTask = URLSessionDataTask()
    var session: SessionProtocol = URLSession.shared
    var request: URLRequest?

    func call(method: HTTPMethod, endpoint: T, urlParams: [String: String], bodyParams: [String: String], queryParams: [String: String]) -> Promise<U> {
        return Promise<U> { seal in
            request = try? createRequest(
                service: endpoint.service,
                path: createRoute(path: endpoint.path, urlParams: urlParams),
                bodyParams: bodyParams,
                queryParams: queryParams,
                isFastPatch: method == .JSONPATCH
            )
   .......
}

我正在尝试将其实例化如下

struct RecognitionService: RecognitionServiceProtocol {


    lazy var httpClient: HTTPClientProtocol = HTTPClient<FeedsEndpoint, Recognition>()

}

但我收到错误

Protocol 'HTTPClientProtocol' can only be used as a generic constraint because it has Self or associated type requirements

是使 call func 通用而不是 class 的唯一解决方案吗?

我不确定如何解决这个问题。

尝试

func call<T: EndpointProtocol>(method: HTTPMethod, endpoint: T, urlParams: [String: String], bodyParams: [String: String], queryParams: [String: String]) -> Promise<U>

现在 Swift 有足够的信息来了解您打算如何使用端点。

试试这个:

struct RecognitionService: RecognitionServiceProtocol {

  let httpClient: HTTPClientProtocol = HTTPClient<FeedsEndpoint, Recognition>()

}