我正在尝试制作一个基于 Moya 和 Object Mapper 的通用请求处理程序类。基本上,我想要一个对 Moya 目标执行请求并对成功和失败情况执行一些基本处理的方法:
基于这个答案,我的课程将是这样的:
class APIRequestHandler<T: Mappable> {
let provider = APIManager().getAPIProvider() // Moya provider
func performRequest(target: Target, completionHandler: (response: T?, error: StoreError?) -> Void) {
provider.request(target) { result in
switch result {
case let .Success(response):
switch response.statusCode {
case 200..<300:
do {
let json = try NSJSONSerialization.JSONObjectWithData(response.data, options: .MutableContainers)
let contractualDocument = Mapper<T>().map(json)
completionHandler(response: contractualDocument!, error: nil)
} catch _ {
// Unexpected error when the response can't be parsed
completionHandler(response: nil, error: StoreError.UnexpectedError)
}
case 500:
completionHandler(response: nil, error: StoreError.ServerError)
default:
completionHandler(response: nil, error: StoreError.HTTPError(statusCode: response.statusCode))
}
case .Failure(_):
completionHandler(response: nil, error: StoreError.NetworkError)
}
}
}
}
我的问题是我是否可以在函数级别而不是类级别使用泛型获得相同的结果:
func performRequest<T: Mappable>(target: Target, completionHandler: (response: T?, error: StoreError?) -> Void) {
provider.request(target) { result in
switch result {
case let .Success(response):
// blah, blah
case .Failure(_):
// bleh, bleh
}
}
}
我已经尝试过了,但我的代码出现了构建错误:
Generic parameter "T" could not be inferred