[英]Error trying to return protocol associated type from method
I need to search for entities(photos, albums, etc) using unsplash.com search APIs.我需要使用 unsplash.com 搜索 API 搜索实体(照片、相册等)。 In order to reach reusability and not having to create a new function every time i need to search for a new entity i created a protocol:
为了达到可重用性并且不必每次需要搜索新实体时都创建新函数,我创建了一个协议:
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 }
}
And a structure conforming to that protocol:以及符合该协议的结构:
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!
}
}
Now I want to create a function that will accept an struct or class conforming to SearchApiResource protocol:现在我想创建一个函数来接受符合 SearchApiResource 协议的结构或类:
func searchForItem(resource: SearchApiResource, searchTerm: String, pageNumber: Int, completion: @escaping (SearchApiResource.ModelType) -> Void ) {
}
But I receive an error: "Associated type 'ModelType' can only be used with a concrete type or generic parameter base"但我收到一个错误:“关联类型‘ModelType’只能与具体类型或通用参数库一起使用”
How to fix an error and what am i doing wrong?如何修复错误以及我做错了什么?
Just do what the error says - use SearchApiResource
as a generic parameter base.只需按照错误说明进行操作 - 使用
SearchApiResource
作为通用参数库。
func searchForItem<T: SearchApiResource>(resource: T, searchTerm: String, pageNumber: Int, completion: @escaping (T.ModelType) -> Void ) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.