Swift how to get different types as paramaters? Enums vs Switch case?

Viewed 28

I have three different data fetching methods like the following sample. Three different methods should return different decodable types. The only difference between these methods is the Type that they would be parsed into. Obviously three different methods is just code duplication.

It works that way but I want to simplify and refactor that methods. I have three different response types. I guess I need to use switch case with some enum or use enums as parameters. But I don't know how to do that.

func fetchProducts(with parameters: CategoryParams, completion: @escaping (ProductsResponse) -> Void) {
        AF.request(productURL, method: .get, parameters: parameters, headers: headers).responseDecodable(of: ProductsResponse.self) { res in
        switch res.result {
        case .success:
            DispatchQueue.main.async {
                completion(res.value!)
            }
        case .failure(let error):
            print(error)
        }
    }
}
1 Answers

Generic! you should input the specific type that you want to decode.

func fetchProducts<RespType>(with parameters: CategoryParams, respType: RespType.Type, completion: @escaping (RespType) -> Void) {
  AF.request(productURL, method: .get, parameters: parameters, headers: headers).responseDecodable(of: RespType.self) { res in
    switch res.result {
    case .success:
      DispatchQueue.main.async {
          completion(res.value!)
      }
    case .failure(let error):
      print(error)
    }
  }
}
Related