调用方法时无法推断通用参数“ T”

时间:2019-11-10 20:18:29

标签: ios swift iphone generics swift5

我遇到错误 无法推断出通用参数“ T”

我创建了一个方法,当我尝试调用该方法时遇到该错误。我在下面添加了这两种方法。

 func requestNew<T> ( _ request: URLRequest, completion: @escaping( Result< T ,  NetworkError>) -> Void ) where T : Decodable {

         URLCache.shared.removeAllCachedResponses()

    print("URL \((request.url as AnyObject).absoluteString ?? "nil")")
        //use the currentrequest for cancel or resume alamofire request
        currentAlamofireRequest =   self.sessionManager.request(request).responseJSON { response in
             //validate(statusCode: 200..<300)
            if response.error != nil {
                var networkError : NetworkError = NetworkError()
                networkError.statusCode = response.response?.statusCode
                if response.response?.statusCode == nil{
                    let error = (response.error! as NSError)
                    networkError.statusCode = error.code
                }
                //Save check to get the internet connection is on or not
                if self.reachabilityManager?.isReachable == false {
                    networkError.statusCode = Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue)

                }

                completion(.failure(networkError))
            }else{
                print("response --- > ",String(data: response.data!, encoding: .utf8) ?? "No Data found")
                if let responseObject = try? JSONDecoder().decode(T.self, from: response.data!) {
                    completion(.success(responseObject.self))
                }else {
                }

            }
        }
    }

以下是错误的屏幕截图 ![ ] 1

func getVersion1(complete :@escaping (Response<Version>) -> Void, failure:@escaping onFailure) {
self.network.requestNew(self.httpRequest) { (result) in
    print("hello")
}

1 个答案:

答案 0 :(得分:2)

当Swift无法推断出通用参数时,尽管它接受方法的通用声明,但是您可以通过传递 type固定参数来指定类型。

尝试一下:

    func getVersion1(complete :@escaping (Response<Version>) -> Void, failure:@escaping onFailure) {
        self.network.requestNew(self.httpRequest) { (result: Result<Version, NetworkError>) in
            print("hello")
        }
    }

如果Result<Version, NetworkError>不是请求中期望的类型,则可能需要将Result<SomeDecodableType, NetworkError>更改为Version