所以,我使用的是来自github的alamofire和object mapper库。在我的函数中有这个代码Alamofire.request(urlRequest).responseObject { (response: DataResponse<News>) in }我还将响应与状态代码一起进行检查switch response.result { case .success: if let object = responseObject { completion(object) } break; case .failure(let error): print(error) if let statusCode = response.response?.statusCode { var message = String() switch statusCode { //status code checking here } } else { var message = String() message = error.localizedDescription } break; }所以我有几个api调用,所有的api调用也将实现这个状态代码检查。我不想为我所有的api调用函数一直复制粘贴这段代码所以我计划做的是创建一个专用函数来检查来自api调用的状态代码但我面临一个问题。如何创建接受所有类型数据响应的泛型函数参数?我试图运行此代码,但失败了// validateResponse functionstatic func validateResponse(dataResponse: DataResponse<Any>) -> String { // status code checking here}// inside the alamofire.request responsevalidateResponse(dataResponse: response)// return me this errorCannot convert value of type 'DataResponse<News>' to expected argument type 'DataResponse<Any>'dataresponse将始终根据提供给alamofire.responseobject的模型进行更改有人能教我怎么做吗?谢谢! (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 你需要使用泛型!static func validateResponse<T>(dataResponse: DataResponse<T>) -> String { // status code checking here}用法:validateResponse(dataResponse: response)一般参数T将被推断为News它将好像方法如下:static func validateResponse(dataResponse: DataResponse<News>) -> String { // status code checking here} (adsbygoogle = window.adsbygoogle || []).push({});
10-08 01:05