无法推断出通用参数

时间:2017-06-21 12:49:38

标签: ios swift generics alamofire

这里我有一个函数创建一个DataResponseSerializer,其泛型类型为 T

extension DataResponseSerializer {
     static func mappableObjectSerializer<T: Mappable>() -> DataResponseSerializer<T> {...}
}

另一个带有执行请求的函数的扩展,它返回一个名为 SuccessObjectType 的泛型类型,在这一个中我调用上面的函数。

public extension DataRequest { 
      @discardableResult func requestObject<SuccessObjectType: Mappable>(onSuccess success: @escaping  ((SuccessObjectType?) -> Void),
                      onFailure failure: @escaping ((NSError?) -> Void),
                      onCompletion completion: (() -> Void)? = nil) -> Self {

    let responseSerializer = DataResponseSerializer<SuccessObjectType>.mappableObjectSerializer()

    return response(queue: nil, responseSerializer: responseSerializer, completionHandler: { (response) in
        switch response.result {...})
}

}

我的想法是将序列化程序与请求本身解除关联,因此我可以在遗留项目上实现UnitTest,但由于某种原因我得到了错误

  

无法推断通用参数“T”

在线:

let responseSerializer = DataResponseSerializer<SuccessObjectType>.mappableObjectSerializer()

1 个答案:

答案 0 :(得分:0)

感谢这个答案Cannot explicitly specialize a generic function我可以找到解决方法,这很简单,从这个:

let responseSerializer = DataResponseSerializer<SuccessObjectType>.mappableObjectSerializer()

对此:

let responseSerializer: DataResponseSerializer<SuccessObjectType> = DataResponseSerializer<SuccessObjectType>.mappableObjectSerializer()

它的作用是从函数中输入预期的返回值,这样编译就知道函数会发生什么。