如何快速将类型传递给具有通用类型的调用的函数

时间:2019-06-17 19:45:07

标签: swift generics callback closures

使用具有泛型值的完成处理程序调用函数会在xcode中给出有关泛型类型的错误,函数定义为:

 func loadData<T: Codable>(params: parameters, completion: @escaping (resultados<T>) -> Void) {
    let request = requestManager()
    request.post(params: params, with: {result in
        switch result{
        case .success(let data):
            do {
                let mydata = try JSONDecoder().decode(T.self, from: data)
                completion(.datos(Dato: mydata))
            }
            catch{
                completion(.error(Error: error))
            }
        case .failure(let error):
            completion(.error(Error: error))
        }
    })
}

resultados是这样的枚举:

    enum resultados<T>{
    case datos(Dato: T)
    case error(Error: Error)
    }

该函数基于T类型发出请求并解码响应。但是在调用该函数时,由于该代码不起作用,如何确定泛型类型是可能的:

let dat = dataLoader()
dat.loadData<T:productResponse>(params: parameters.Endpoint(endpoint: end), completion:{ result in
            switch result{
            case .datos(let Dato):
                self.mydata = Dato as? productResponse
                self.stopanAnimation()
                DispatchQueue.main.async {
                    self.performSegue(withIdentifier: "showResult", sender: self)
                }
            case .error(let error):
                self.stopanAnimation()
            }
        })

因为xcode说 enter image description here 并删除T以这样离开dat.loadData<productResponse>(params: parameters.Endpoint(endpoint: end), completion:{ result in 然后xcode说

  

不能显式专门化泛型函数

编辑: 这个问题的全部重点是尝试使编译器能够推断类型,或者用一种方法说出具有泛型值的枚举的类型,因为函数参数没有枚举内部的回调类型不是可以推断,这是行不通的,但要表达我的意思的代码。

func loadData<T:Codable>(params: parameters,completion: @escaping (resultados<T>) -> Void)

因为resultados是带有符合codable的泛型的枚举。我想以一种可以通过解码类型的方式调用该函数。像这样

    let dec = dataLoder()
    dec.dataLoader<T:productResponse>(params: parameters,completion: { result in)
result in the completion is another enum with this format:

    enum resultados<T>{
    case datos(Dato: T)
    case error(Error: Error)
    }
so i have to swich the enum and obtain the decoded value. guess this is not posible in swift with the above o any other way for the compiler reconigze it.




1 个答案:

答案 0 :(得分:0)

定义一个特定的处理函数:

func resultadosHandler(resultados: resultados<productResponse>) { // productResponse is the type you expect
    switch resultados {
    case .datos(let dato): print(dato)
    case .error(let error): print(error)
    }
}

将其传递给加载器功能:

dat.loadData(params: parameters.Endpoint(endpoint: end), completion: resultadosHandler)

或者,如果您愿意,也可以像下面这样使用内联模式:

loadData(params: parameters.Endpoint(endpoint: end)) { (resultados: resultados<productResponse>) in
    switch resultados {
    case .datos(let dato): print(dato)
    case .error(let error): print(error)
    }
}

别忘了用正确的实现方式替换打印件!