Swift泛型属性作为泛型闭包的值

时间:2017-01-19 17:45:21

标签: swift generics mocking alamofire swift-protocols

我一直在旋转我的轮子,暂时没有。我正在尝试为可序列化对象创建一个Alamofire模拟类。

我有一个协议:

protocol AlamofireManagerInterface {
    func apiRequest<T: ResponseObjectSerializable>(withMethod method: Alamofire.Method,
        forURLString URLString: URLStringConvertible,
        withParameters parameters: [String: AnyObject]?,
        withEncoding encoding: ParameterEncoding,
        withHeaders headers: [String: String]?,
        completion completionHandler: (Response<T, NSError> -> Void))
}

这允许我创建符合界面的模拟,如下所示:

class AlamofireManagerInterfaceMock<ResponseType: ResponseObjectSerializable> {
    var functionsCalled = [String]()

    // MARK: - Input Variables
    var forURLString: URLStringConvertible?
    var completionHandlerResponseValue: Response<ResponseType, NSError>?
    var shouldCallCompletion = false
    var withEncoding: ParameterEncoding?
    var withHeaders: [String: String]?
    var withMethod: Alamofire.Method?
    var withParameters: [String: AnyObject]?

    // MARK: - Return Values
}

extension AlamofireManagerInterfaceMock: AlamofireManagerInterface {
    func apiRequest<T: ResponseObjectSerializable>(withMethod method: Alamofire.Method,
         forURLString URLString: URLStringConvertible,
         withParameters parameters: [String: AnyObject]? = nil,
         withEncoding encoding: ParameterEncoding = .URL,
         withHeaders headers: [String: String]? = nil,
         completion completionHandler: (Response<T, NSError> -> Void)) {

    // Parameter capturing - removed

    if let value = completionHandlerResponseValue {
        // Problem is here
        completionHandler(value)
    }
}

所以我的问题是如何告诉编译器我的completionHandlerResponeValue应该与要传递给completionHandler的参数的类型相同?

我在这里收到错误:

if let value = completionHandlerResponseValue {
    completionHandler(value)
    // Error: Cannot convert value of type 'Response<ResponseType, NSError>' 
    // to expected argument type 'Response<_, NSError>'
}

我尝试了很多关于类型转换的事情,例如:

if let value = completionHandlerResponseValue as Response<T, NSError>
// Error: Cannot convert value of type 'Response<ResponseType, NSError>?'
// to type 'Response<_, NSError>' in coercion

尝试强制转换处理程序:

if let handler = completionHandler as (Response<ResponseType, NSError> -> Void)
// Error: Cannot convert value of type 'Response<T, NSError> -> Void' 
// to type 'Response<_, NSError> -> Void' in coercion

可选择施放:

if let value = completionHandlerResponseValue as? Response<T, NSError> {
// Warning: Cast from 'Response<ResponseType, NSError>?' to unrelated 
// type 'Response<T, NSError>' always fails
    completionHandler(response)
}

0 个答案:

没有答案