swift4:使用func泛型类型指定另一个func的泛型类型

时间:2018-08-16 15:19:21

标签: ios swift alamofire objectmapper

我想在自己的函数请求中指定数据响应的类型

func request<T>(urlString: String, method: HTTPMethod, parameters: Parameters, headers: HTTPHeaders,
                callBack:@escaping (T) -> Void,
                failureHandler:@escaping (Error) -> Void) {

    Alamofire.request(urlString, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: nil).validate().responseObject { (response: DataResponse<T>) in
        <#code#>
    }

}

1 个答案:

答案 0 :(得分:0)

您当然可以做到。

func request<T: BaseMappable>(urlString: String, method: HTTPMethod, parameters: Parameters, headers: HTTPHeaders,
                callBack:@escaping (T) -> Void,
                failureHandler:@escaping (Error) -> Void) {

    Alamofire.request(urlString, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: nil).validate().responseObject { (response: DataResponse<T>) in
        switch response.result {
        case .success(let result):
            callBack(result)
        case .failure(let error):
            failureHandler(error)
        }
    }
}