尝试从方法返回协议关联类型时出错

时间:2019-12-29 10:23:10

标签: ios swift api

我需要使用unsplash.com搜索API搜索实体(照片,相册等)。为了达到可重用性,而不必每次需要搜索新实体时都创建新功能,所以我创建了一个协议:

protocol SearchApiResource {

    associatedtype ModelType: Decodable

    var methodPath: String { get }

    var searchTerm: String { get set }

    var pageNumber: Int { get set }

    var parameters: [String: String] { get }

    var url: URL { get }
}

以及符合该协议的结构:

struct SearchPhotoResource: SearchApiResource {

    typealias ModelType = Photo

    var methodPath = "/search/photos"

    var searchTerm = String()

    var pageNumber = Int()

    let itemsPerPage = 30

    let accessKey = "93e0a185df414cc1d0351dc2238627b7e5af3a64bb228244bc925346485f1f44"

    var parameters: [String: String] {
        var params = [String: String]()
        params["query"] = searchTerm
        params["page"] = String(pageNumber)
        params["per_page"] = String(itemsPerPage)
        params["client_id"] = accessKey
        return params
    }

    var url: URL {
        var components = URLComponents()
        components.scheme = "https"
        components.host = "api.unsplash.com"
        components.path = methodPath
        components.queryItems = parameters.map {URLQueryItem(name: $0, value: $1)}
        return components.url!
    }

}

现在,我想创建一个函数,该函数将接受符合SearchApiResource协议的结构或类:

func searchForItem(resource: SearchApiResource, searchTerm: String, pageNumber: Int, completion: @escaping (SearchApiResource.ModelType) -> Void ) {
}

但是我收到一个错误: “关联类型'ModelType'只能与具体类型或通用参数库一起使用”

如何解决错误,我在做什么错?

1 个答案:

答案 0 :(得分:2)

只需执行错误所说明的内容-使用SearchApiResource作为通用参数库即可。

func searchForItem<T: SearchApiResource>(resource: T, searchTerm: String, pageNumber: Int, completion: @escaping (T.ModelType) -> Void ) {
}