【发布时间】:2019-10-31 10:32:12
【问题描述】:
使用具有泛型值的完成处理程序调用函数在 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 说
并删除 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 是带有符合可编码的泛型的枚举。我想以可以传递解码类型的方式调用该函数。像这样的
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.
【问题讨论】:
-
您应该注意 Swift 命名约定
ProductResponse并为您的实例变量和常量使用小写 -
查看我的答案。
标签: swift generics callback closures