我如何修复协议只能用作通用约束,因为它具有Self或关联类型要求错误

问题描述 投票:0回答:2

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

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

我有一个协议

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 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>()

}

但是我得到了错误

协议'HTTPClientProtocol'只能用作通用约束,因为它具有Self或关联类型要求

是唯一的解决方案,使call功能通用而不是类?

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

ios swift generics swift-protocols
2个回答
0
投票

尝试

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

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


0
投票

试试这个:

struct RecognitionService: RecognitionServiceProtocol {

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

}
© www.soinside.com 2019 - 2024. All rights reserved.