我试图了解我可以在协议中使用泛型的数量。我想到的想法如下:
protocol Network {
func fetchCodable<T:Codable>(urlRequest:URLRequest, completion:@escaping (Result<T,Error>)->Void)
}
然后,我创建一个名为AppNetwork的类,该类实现网络协议。
extension AppNetwork:Network{
func fetchCodable<T>(urlRequest: URLRequest, completion: @escaping (Result<T, Error>) -> Void) where T : Decodable, T : Encodable {
URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else{
completion(.failure(AppNetworkError.dataCorrupted))
return
}
do {
let response = try JSONDecoder().decode(T.self, from: data)
completion(.success(response))
}
catch let decodeError{
completion(.failure(decodeError))
}
}.resume()
}
此类是NetworkHelper的一部分,该类实现用于检索数据的功能,例如:
class NetworkHelper{
let network:Network = AppNetwork()
}
...
//MARK:- Public methods
extension NetworkHelper{
func getVenueDetails(inLocation:String, offset:Int, limit:Int, radius:Int = 1000,completion:(Result<VenueDetailsSearchResult, Error>)->Void){
guard let foursquareConfig = foursquareConfig else{
completion(.failure(NetworkHelper.NetworkHelperError.invalidFourSquareConfig))
return
}
var venuesURLString = EndPoints.venueSearch.rawValue + "?"
venuesURLString += foursquareConfig.getFormattedParams
venuesURLString += "&near=\(inLocation)&radius=\(radius)&offset=\(offset)&limit=\(limit)"
guard let venuesURL = URL(string: venuesURLString) else{
completion(.failure(NetworkHelper.NetworkHelperError.invalidURL))
return
}
let venuesURLRequest = URLRequest(url: venuesURL, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
network.fetchCodable(urlRequest: venuesURLRequest) { result in
}
}
}
在这种情况下,我试图获取结果,但收到一条消息错误:“无法推断出通用参数'T'”
如果我可以那样做怎么办?
谢谢
答案 0 :(得分:2)
您必须将所需的类型告诉编译器。
network.fetchCodable(urlRequest: venuesURLRequest) { (_ result: Result<VenueDetailsSearchResult, Error>) in
// ...
}